onError method

  1. @override
Future onError(
  1. DioException err,
  2. ErrorInterceptorHandler handler
)

Intercepts errors to handle token refresh if necessary.

If the error indicates that the token should be refreshed, uses the tokenRefreshStrategy to refresh the token. If successful, retries the original request with the new token. If the refresh fails, clears the tokens using the tokenManager and rejects the request with a TokenRefreshException.

Implementation

@override
Future onError(DioException err, ErrorInterceptorHandler handler) async {
  if (tokenRefreshStrategy.shouldRefreshToken(err.response!)) {
    try {
      final newAccessToken =
          await tokenRefreshStrategy.refreshToken(Dio(), tokenManager);
      if (newAccessToken != null) {
        final headers =
            tokenRefreshStrategy.getAuthorizationHeaders(newAccessToken);
        err.requestOptions.headers.addAll(headers);
        final cloneReq = await Dio().request(
          err.requestOptions.path,
          options: Options(
            method: err.requestOptions.method,
            headers: err.requestOptions.headers,
          ),
        );
        return handler.resolve(cloneReq);
      } else {
        return handler.next(err);
      }
    } catch (e) {
      await tokenManager.clearTokens();
      return handler.next(DioException(
        requestOptions: err.requestOptions,
        error: TokenRefreshException(
            TokenErrorMessages.failedToRefreshAccessToken),
      ));
    }
  }
  return handler.next(err);
}