On this page
error_outline
Error Handling
Catches specific exception types by runtimeType and routes each to a typed handler. Unmatched exceptions are either handled by catchAll or rethrown.
Error Handling
Error-handling decorators catch exceptions and convert them into fallback values or typed recovery paths. They are similar to reliability decorators but focused on deterministic error translation rather than transient failure recovery.
catchError
What it is
Catches specific exception types by runtimeType and routes each to a typed handler. Unmatched exceptions are either handled by catchAll or rethrown.
When to use it
- Mapping domain exceptions to fallback values
- Converting errors into user-friendly results
- Centralized exception handling for a function
Async / sync support
Func<R> | Func1<T, R> | Func2<T1, T2, R> | FuncSync<R> |
|---|---|---|---|
| ✅ | ✅ | ✅ | ❌ |
API reference
| |
handlers— map oferror.runtimeTypeto handler function.catchAll— fallback handler for unmatched exceptions.onCatch— called for every caught exception before the handler runs.
Examples
Minimal
| |
Real world
| |
Best practices
- Put the most specific exception types first in the map.
- Use
catchAllfor logging unexpected failures.
Common pitfalls
- Matching is by exact
runtimeType; aSocketExceptionhandler will not catch aClientException. - Handlers are checked in iteration order; map order matters.
defaultValue
What it is
Returns a static default value when the wrapped function throws. An optional predicate controls which errors trigger the default.
When to use it
- Non-critical reads where any value is better than an exception
- Ensuring non-null results
- Simple fail-safe defaults
Async / sync support
Func<R> | Func1<T, R> | Func2<T1, T2, R> | FuncSync<R> |
|---|---|---|---|
| ✅ | ✅ | ✅ | ❌ |
API reference
| |
defaultValue— value returned on failure.defaultIf— if provided and returnsfalse, the error is rethrown.onDefault— called when the default is used.
Examples
Minimal
| |
Real world
| |
Best practices
- Use
defaultIfto avoid masking critical errors. - Keep the default value immutable if possible.
Common pitfalls
defaultValueis evaluated once when the decorator is created; if it is mutable, all failures share the same instance.