Sub topic 14
Interceptors for logging, auth and retries
This chapter assumes that you know Dart classes, Future, async and await, basic Flutter widgets, and the Dio package. An interceptor is code that runs around a request. It can change a request before it is sent, inspect a response, or handle an error.
Interceptors are useful when many requests need the same policy:
- Add an
Authorizationheader. - Log request and response details.
- Retry a temporary network failure.
- Convert or report errors consistently.
Where an interceptor runs
Dio passes each request through the interceptor chain. The request interceptor runs first. After the server responds, Dio calls either the response interceptor or the error interceptor.
Call handler.next(value) to continue the chain. Call handler.resolve(response) when an interceptor has produced a successful response. Call handler.reject(error) or handler.next(error) to continue with a failure.
Adding authentication and logging
A request interceptor can read a token from secure storage and attach it to every request. Keep token storage outside the interceptor. Inject a function or service so the interceptor remains easy to test.
Do not log the token or sensitive request bodies. Logs often go to systems that have wider access than the application.
import 'dart:developer' as developer;
import 'package:dio/dio.dart';
typedef TokenReader = Future<String?> Function();
class ApiInterceptor extends Interceptor {
ApiInterceptor({required this.readToken});
final TokenReader readToken;
@override
Future<void> onRequest(
RequestOptions options,
RequestInterceptorHandler handler,
) async {
final token = await readToken();
if (token != null && token.isNotEmpty) {
options.headers['Authorization'] = 'Bearer $token';
}
developer.log(
'${options.method} ${options.uri}',
name: 'api.request',
);
handler.next(options);
}
@override
void onResponse(Response<dynamic> response,
ResponseInterceptorHandler handler) {
developer.log(
'${response.statusCode} ${response.requestOptions.uri}',
name: 'api.response',
);
handler.next(response);
}
@override
void onError(
DioException error,
ErrorInterceptorHandler handler,
) {
developer.log(
'${error.requestOptions.method} '
'${error.requestOptions.uri}: ${error.message}',
name: 'api.error',
);
handler.next(error);
}
}
final dio = Dio(
BaseOptions(
baseUrl: 'https://api.example.com',
connectTimeout: const Duration(seconds: 5),
receiveTimeout: const Duration(seconds: 10),
),
);
void configureDio(Future<String?> Function() readToken) {
dio.interceptors.add(ApiInterceptor(readToken: readToken));
}A 401 Unauthorized response usually means that the access token is missing or expired. Refreshing a token inside onError requires extra coordination. Only one refresh should run at a time, and the original request should be retried once. Otherwise, an expired token can create an infinite loop.
Retrying safely
A retry is appropriate for temporary failures such as a connection timeout or a server-side 503 response. Retry only idempotent operations by default. An idempotent operation can be repeated without creating another side effect. GET is normally idempotent. POST may create a second resource if repeated.
A simple policy can retry a GET once:
class RetryInterceptor extends Interceptor {
RetryInterceptor(this.dio);
final Dio dio;
@override
Future<void> onError(
DioException error,
ErrorInterceptorHandler handler,
) async {
final request = error.requestOptions;
final method = request.method.toUpperCase();
final status = error.response?.statusCode;
final temporary = error.type == DioExceptionType.connectionTimeout ||
error.type == DioExceptionType.receiveTimeout ||
status == 502 ||
status == 503 ||
status == 504;
if (method == 'GET' &&
temporary &&
request.extra['retried'] != true) {
request.extra['retried'] = true;
await Future<void>.delayed(const Duration(milliseconds: 300));
try {
final response = await dio.fetch(request);
handler.resolve(response);
return;
} on DioException catch (retryError) {
handler.next(retryError);
return;
}
}
handler.next(error);
}
}The extra map prevents repeated retries. In production, use a bounded backoff delay and consider server rate limits. Do not retry authentication failures or validation errors.
Choosing an interceptor strategy
| Need | Suitable approach |
|---|---|
| Add a token to every request | Request interceptor |
| Record timing and status codes | Response and error interceptors |
| Retry temporary `GET` failures | Error interceptor with a retry limit |
| Refresh expired credentials | Coordinated authentication service |
Exercise
Why should a retry interceptor normally avoid POST requests?
Show answer
Repeating a POST can perform the same side effect twice, such as creating duplicate records. Retry it only when the API provides an idempotency key or another explicit guarantee.