onResponse method

  1. @override
Future onResponse(
  1. Response response,
  2. ResponseInterceptorHandler handler
)

Intercepts and processes incoming responses.

Handles 401 Unauthorized responses by removing this interceptor and rejecting the response with a DioException indicating token expiration.

  • response: The HTTP response received from the server.
  • handler: The interceptor handler to continue or reject the response.

Implementation

@override
Future onResponse(
  Response response,
  ResponseInterceptorHandler handler,
) async {
  // Check if the response status code indicates an unauthorized request.
  if (response.statusCode == 401) {
    // Remove this interceptor from Dio to avoid recursion.
    dio.interceptors
        .removeWhere((element) => element is AuthorizationInterceptor);

    // Reject the response with a custom DioException.
    return handler.reject(
      DioException(
        response: response,
        error: 'Bearer Token Expired',
        type: DioExceptionType.unknown,
        requestOptions: response.requestOptions,
      ),
    );
  }
  // Continue with the response if no issues are found.
  return handler.next(response);
}