Movatterモバイル変換


[0]ホーム

URL:


menu
  1. Dart
  2. dart:async
  3. FutureExtensions<T>
  4. onError<E extends Object> method
onError
description

onError<E extends Object> method

Future<T>onError<E extends Object>(
  1. FutureOr<T>handleError(
    1. Eerror,
    2. StackTracestackTrace
    ), {
  2. booltest(
    1. Eerror
    )?,
})

Handles errors on this future.

Catches errors of typeE that this future complete with.Iftest is supplied, only catches errors of typeEwheretest returnstrue.IfE isObject, then all errors are potentially caught,depending only on a suppliedtest.toString()

If the error is caught,the returned future completes with the result of callinghandleErrorwith the error and stack trace.This result must be a value of the same type that this futurecould otherwise complete with.For example, if this future cannot complete withnull,thenhandleError also cannot returnnull.Example:

Future<T> retryOperation<T>(Future<T> operation(), T onFailure()) =>    operation().onError<RetryException>((e, s) {      if (e.canRetry) {        return retryOperation(operation, onFailure);      }      return onFailure();    });

IfhandleError throws, the returned future completeswith the thrown error and stack trace,except that if it throws thesame error object again,then it is considered a "rethrow"and the original stack trace is retained.This can be used as an alternative to skipping theerror intest.Example:

// Unwraps an exceptions cause, if it has one.someFuture.onError<SomeException>((e, _) {  throw e.cause ?? e;});// vs.someFuture.onError<SomeException>((e, _) {  throw e.cause!;}, test: (e) => e.cause != null);

If the error is not caught, the returned futurecompletes with the same result, value or error,as this future.

This method is effectively a more precisely typed versionofFuture.catchError.It makes it easy to catch specific error types,and requires a correctly typed error handler function,rather than justFunction.Because of this, the error handlers must acceptthe stack trace argument.

Implementation

Future<T> onError<E extends Object>(  FutureOr<T> handleError(E error, StackTrace stackTrace), {  bool test(E error)?,}) {  FutureOr<T> onError(Object error, StackTrace stackTrace) {    if (error is! E || test != null && !test(error)) {      // Counts as rethrow, preserves stack trace.      throw error;    }    return handleError(error, stackTrace);  }  if (this is _Future<Object?>) {    // Internal method working like `catchError`,    // but allows specifying a different result future type.    return unsafeCast<_Future<T>>(this)._safeOnError<T>(onError);  }  return this.then<T>((T value) => value, onError: onError);}
  1. Dart
  2. dart:async
  3. FutureExtensions<T>
  4. onError<E extends Object> method
FutureExtensions extension onFuture<T>

[8]ページ先頭

©2009-2025 Movatter.jp