The `catchError` method in Dart handles errors emitted by this Future.
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.
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. |
Future.catchError() returns value of type Future<T>
.
In this example,
Future.error
and pass an error message.catchError
method and print the error message.void main() {
Future<int>.error('Error occurred')
.catchError((error) {
print('Caught error: $error');
});
}
Caught error: Error occurred
In this example,
Future.value
and pass a value (42).catchError
method won't be triggered.void main() {
Future<int>.value(42)
.catchError((error) {
print('Caught error: $error');
});
}
(No output)
In this example,
Future.delayed
and throw an exception after 2 seconds.catchError
method and print the error message.void main() {
Future<int>.delayed(Duration(seconds: 2), () => throw Exception('Delayed error'))
.catchError((error) {
print('Caught error: $error');
});
}
Caught error: Delayed error
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.