onError method

  1. @override
void onError(
  1. DioException error,
  2. ErrorInterceptorHandler handler
)
override

Handles 401 Unauthorized errors (response-and-retry strategy).

If isResponseAndRetry is true and the response status is 401:

  • Attempts to refresh the token
  • If refresh succeeds, retries the original request with the new token
  • If refresh fails and auth is required, rejects with the original error
  • If refresh fails and auth is not required, passes the error through

Non-401 errors are passed through to the next error handler.

Implementation

@override
void onError(DioException error, handler) async {
  if (isResponseAndRetry &&
      error.response?.statusCode == HttpStatus.unauthorized) {
    try {
      final response = await authHandler.refreshTokenCallback(
        error.requestOptions,
      );

      if (response != null) {
        handler.resolve(response);
      } else {
        handler.next(error);
      }
    } catch (e) {
      if (_isAuthRequired(error.requestOptions)) {
        handler.reject(error);
      } else {
        // Auth not required - continue with the original error
        handler.next(error);
      }
    }
  } else {
    handler.next(error);
  }
}