← → or space · progress saves for Continue on the roadmap
Goal
Model domain failures as types you can catch selectively and message clearly.
Step 1 - Simple custom type
class ValidationException implements Exception {
final String field;
final String message;
ValidationException(this.field, this.message);
@override
String toString() => 'ValidationException($field): $message';
}
void main() {
try {
throw ValidationException('email', 'missing @');
} on ValidationException catch (e) {
print(e.field);
print(e.message);
}
}Step 2 - Extending built-in errors
class OutOfStockError extends StateError {
OutOfStockError(String sku) : super('out of stock: $sku');
}ErrorvsExceptionin Dart is conventional:Exceptionfor expected failures,Errorfor programming mistakes. Many apps blur the line; stay consistent in your project.
Step 3 - Carrying a cause
class SaveFailed implements Exception {
final Object cause;
SaveFailed(this.cause);
}
void main() {
try {
throw SaveFailed(ValidationException('id', 'empty'));
} on SaveFailed catch (e) {
print(e.cause);
}
}Practice tasks
- Add
AuthExceptionwithreasonenum{ badPassword, locked, network }. - Catch
ValidationExceptionspecifically, then a genericcatchas last resort in onetry(document why the generic catch exists).