Dart Future catchError()
Syntax & Examples
Future.catchError() method
The `catchError` method in Dart handles errors emitted by this Future.
Syntax of Future.catchError()
The syntax of Future.catchError() method is:
Future<T> catchError(Function onError, { bool test(Object error) })
This catchError() method of Future handles errors emitted by this Future.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
onError | required | A function that will be called when an error is emitted by the Future. The function should accept an error object as its argument. |
test | optional | A predicate function that determines whether the onError function should be called for a specific error. If provided, the onError function will only be called if this predicate returns true. |
Return Type
Future.catchError() returns value of type Future<T>
.
✐ Examples
1 Handling an error from a failed future
In this example,
- We create a future using
Future.error
and pass an error message. - We handle the error using the
catchError
method and print the error message.
Dart Program
void main() {
Future<int>.error('Error occurred')
.catchError((error) {
print('Caught error: $error');
});
}
Output
Caught error: Error occurred
2 Handling no error from a successful future
In this example,
- We create a future using
Future.value
and pass a value (42). - Since there's no error, the
catchError
method won't be triggered.
Dart Program
void main() {
Future<int>.value(42)
.catchError((error) {
print('Caught error: $error');
});
}
Output
(No output)
3 Handling a delayed error
In this example,
- We create a delayed future using
Future.delayed
and throw an exception after 2 seconds. - We handle the error using the
catchError
method and print the error message.
Dart Program
void main() {
Future<int>.delayed(Duration(seconds: 2), () => throw Exception('Delayed error'))
.catchError((error) {
print('Caught error: $error');
});
}
Output
Caught error: Delayed error
Summary
In this Dart tutorial, we learned about catchError() method of Future: the syntax and few working examples with output and detailed explanation for each example.