Error Handling
Part of the Examples. Every exception pdata can throw, triggered on purpose: a missing file, malformed YAML and TOML, a value TOML can’t represent, and an unguessable format.
Source: example/error_handling_example.dart
// Run this example from the package root:
// dart run example/error_handling_example.dart
// print() is fine in example scripts; avoid it in production code instead.
// ignore_for_file: avoid_print
import 'package:pdata/pdata.dart';
void main() {
// 1. Reading a file that doesn't exist.
try {
pdataReadFile('build/does_not_exist.yaml');
} on PdataFileNotFoundException catch (e) {
print('Missing file: $e');
}
// 2. Malformed input for the format being parsed.
try {
decodeYaml('key: [unclosed');
} on PdataParseException catch (e) {
print('Bad YAML: $e');
}
try {
decodeToml('key = ');
} on PdataParseException catch (e) {
print('Bad TOML: $e');
}
// 3. A value that can't be represented in the requested format — TOML
// has no `null`.
try {
encodeToml({'name': 'my-app', 'nickname': null});
} on PdataFormatException catch (e) {
print('Unrepresentable value: $e');
}
// 4. No extension to guess a format from, and none supplied.
try {
pdataWriteFile('build/config', {'a': 1});
} on PdataFormatException catch (e) {
print('Unknown format: $e');
}
// Passing `format:` explicitly sidesteps extension guessing entirely.
pdataWriteFile('build/config', {'a': 1}, format: PdataFormat.json);
print('\nWrote build/config as JSON by passing `format:` explicitly.');
}
Run it from the package root:
dart run example/error_handling_example.dart