Sub topic 14
Interceptors for logging, auth and retries
What you need first
This chapter assumes you have a configured Dio instance with a base URL and timeouts, as in the previous chapter. It also assumes you are comfortable with async/await and Future. You will move three cross-cutting concerns out of individual calls and into reusable classes: logging, authentication and retries.
What an interceptor is
An interceptor is an object that Dio calls at three points in a request's life. Each callback receives a handler that tells Dio what to do next.
| Callback | Runs when | Handler methods |
|---|---|---|
| `onRequest` | Before the request is sent | `next(options)`, `resolve(response)`, `reject(error)` |
| `onResponse` | After a successful response | `next(response)`, `resolve(response)`, `reject(error)` |
| `onError` | After a `DioException` | `next(error)`, `resolve(response)`, `reject(error)` |
Every callback must call exactly one handler method. If you forget, the request hangs forever with no error. This is the most common interceptor bug.
You subclass Interceptor and override only the callbacks you need. The defaults pass the data along with handler.next. Interceptors live in dio.interceptors, a list, and Dio calls them in the order you added them for all three phases.
Logging interceptor
Dio ships LogInterceptor, which is fine while you are learning. It prints headers by default, though, and that includes your Authorization token. A small custom logger gives you control over what is printed.
import 'dart:developer' as developer;
import 'package:dio/dio.dart';
class TimingLogInterceptor extends Interceptor {
static const _startKey = 'startedAtMs';
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
options.extra[_startKey] = DateTime.now().millisecondsSinceEpoch;
handler.next(options);
}
@override
void onResponse(Response<dynamic> response, ResponseInterceptorHandler handler) {
_log(response.requestOptions, '${response.statusCode}');
handler.next(response);
}
@override
void onError(DioException err, ErrorInterceptorHandler handler) {
final status = err.response?.statusCode;
_log(err.requestOptions, status?.toString() ?? err.type.name);
handler.next(err);
}
void _log(RequestOptions options, String outcome) {
final started = options.extra[_startKey] as int?;
final elapsed =
started == null ? '?' : '${DateTime.now().millisecondsSinceEpoch - started}';
developer.log(
'${options.method} ${options.uri.path} -> $outcome (${elapsed}ms)',
name: 'http',
);
}
}The options.extra map travels with the request, so it is the right place for per-request state such as a start time. The logger prints the method, path, outcome and duration, and never the headers or body.
Auth interceptor
Attaching the token in one place means no call site can forget it. Read the token on every request instead of capturing it once, because it changes after a refresh.
class AuthInterceptor extends Interceptor {
AuthInterceptor(this._readToken);
final Future<String?> Function() _readToken;
@override
Future<void> onRequest(
RequestOptions options,
RequestInterceptorHandler handler,
) async {
final token = await _readToken();
if (token != null) {
options.headers['Authorization'] = 'Bearer $token';
}
handler.next(options);
}
}Refreshing an expired token
When the server answers 401, the interceptor refreshes the token once and repeats the request. Three details matter:
- Mark the retried request in
extra, so a second 401 is returned to the caller instead of looping. - Share one in-flight refresh between concurrent requests. Without this, five parallel 401s trigger five refresh calls, and refresh tokens are often single-use.
- Call the refresh endpoint through a different
Dioinstance. If it used this instance, a failing refresh would trigger another refresh.
class RefreshInterceptor extends Interceptor {
RefreshInterceptor(this._dio, this._refreshToken);
final Dio _dio;
/// Stores the new token and returns it, or returns null if refresh failed.
/// It must use its own Dio instance.
final Future<String?> Function() _refreshToken;
Future<String?>? _refreshing;
Future<String?> _refreshOnce() =>
_refreshing ??= _refreshToken().whenComplete(() => _refreshing = null);
@override
Future<void> onError(DioException err, ErrorInterceptorHandler handler) async {
final options = err.requestOptions;
final alreadyRetried = options.extra['authRetried'] == true;
if (err.response?.statusCode != 401 || alreadyRetried) {
handler.next(err);
return;
}
final newToken = await _refreshOnce();
if (newToken == null) {
handler.next(err);
return;
}
options.extra['authRetried'] = true;
try {
// AuthInterceptor adds the new token when the request passes through again.
handler.resolve(await _dio.fetch<dynamic>(options));
} on DioException catch (e) {
handler.next(e);
}
}
}Retry interceptor
Retries help with brief network failures and overloaded servers. They are dangerous when the request is not safe to repeat. A retried POST /orders can create two orders. Retry only idempotent methods, meaning methods where repeating the call has the same effect as making it once. These are GET, HEAD, PUT, DELETE and OPTIONS.
The interceptor below retries timeouts, connection errors and 502, 503 and 504 responses. It waits longer after each attempt (exponential backoff: 0.5 s, 1 s, 2 s).
class RetryInterceptor extends Interceptor {
RetryInterceptor(
this._dio, {
this.maxRetries = 3,
this.baseDelay = const Duration(milliseconds: 500),
});
final Dio _dio;
final int maxRetries;
final Duration baseDelay;
static const _safeMethods = {'GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS'};
static const _retryableStatuses = {502, 503, 504};
bool _shouldRetry(DioException err) {
if (!_safeMethods.contains(err.requestOptions.method.toUpperCase())) {
return false;
}
switch (err.type) {
case DioExceptionType.connectionTimeout:
case DioExceptionType.sendTimeout:
case DioExceptionType.receiveTimeout:
case DioExceptionType.connectionError:
return true;
case DioExceptionType.badResponse:
return _retryableStatuses.contains(err.response?.statusCode);
default:
return false;
}
}
@override
Future<void> onError(DioException err, ErrorInterceptorHandler handler) async {
final options = err.requestOptions;
final attempt = (options.extra['retryCount'] as int?) ?? 0;
if (!_shouldRetry(err) || attempt >= maxRetries) {
handler.next(err);
return;
}
options.extra['retryCount'] = attempt + 1;
await Future<void>.delayed(baseDelay * (1 << attempt));
try {
handler.resolve(await _dio.fetch<dynamic>(options));
} on DioException catch (e) {
handler.next(e);
}
}
}The retried call passes through the whole chain again, so the nested call handles any further retries. When it finally fails, the outer callback passes that error on without retrying a second time.
Wiring the chain
Order matters because Dio runs callbacks in list order in every phase.
Dio buildDio({
required Future<String?> Function() readToken,
required Future<String?> Function() refreshToken,
}) {
final dio = Dio(
BaseOptions(
baseUrl: 'https://jsonplaceholder.typicode.com',
connectTimeout: const Duration(seconds: 5),
receiveTimeout: const Duration(seconds: 10),
),
);
dio.interceptors.addAll([
TimingLogInterceptor(),
AuthInterceptor(readToken),
RefreshInterceptor(dio, refreshToken),
RetryInterceptor(dio),
]);
return dio;
}The logger comes first, so it never sees the Authorization header that AuthInterceptor adds later. Each retry re-enters the chain, so the logger records every attempt separately. A 401 reaches RefreshInterceptor before RetryInterceptor, and a 503 passes through the refresh interceptor untouched.
Testing an interceptor without a network
Dio lets you replace its HttpClientAdapter, the layer that actually sends bytes. A fake adapter that fails twice and then succeeds proves the retry logic.
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:flutter_test/flutter_test.dart';
class FlakyAdapter implements HttpClientAdapter {
int calls = 0;
@override
Future<ResponseBody> fetch(
RequestOptions options,
Stream<Uint8List>? requestStream,
Future<void>? cancelFuture,
) async {
calls++;
if (calls < 3) {
return ResponseBody.fromString('unavailable', 503);
}
return ResponseBody.fromString(
'{"id": 1}',
200,
headers: {
Headers.contentTypeHeader: [Headers.jsonContentType],
},
);
}
@override
void close({bool force = false}) {}
}
void main() {
test('RetryInterceptor retries 503 until the call succeeds', () async {
final adapter = FlakyAdapter();
final dio = Dio(BaseOptions(baseUrl: 'https://example.test'))
..httpClientAdapter = adapter;
dio.interceptors.add(RetryInterceptor(dio, baseDelay: Duration.zero));
final response = await dio.get<Map<String, dynamic>>('/items/1');
expect(response.statusCode, 200);
expect(response.data!['id'], 1);
expect(adapter.calls, 3);
});
}Place RetryInterceptor (and the other classes) in a file this test imports. Setting baseDelay to Duration.zero keeps the test fast.
Common mistakes
- Forgetting a handler call. Every path through every callback, including early returns and
catchblocks, must callnext,resolveorreject. - Retrying non-idempotent requests. Retrying POST needs a server-side idempotency key. Without one, do not retry it.
- Unbounded loops. Without a counter in
extra, a permanent 503 retries forever. - Logging secrets. Do not print tokens, passwords or full request bodies in release builds.
- Refreshing through the same client. The refresh call must bypass the refresh logic.
Exercise
A user taps "Place order" and the app sends POST /orders. The connection drops after the request is sent but before the response arrives. Why is it unsafe for RetryInterceptor to retry this request, and what would you add to make a retry safe?
Show answer
The server may have already created the order. A retry would then create a second one, because POST is not idempotent. A retry becomes safe if the client sends an idempotency key (a unique ID in a header such as Idempotency-Key) that the server uses to detect and ignore a duplicate, or if the server endpoint is changed to be idempotent, for example PUT /orders/{clientGeneratedId}.
Exercise
Three requests run at the same time and all receive 401. In RefreshInterceptor, how many refresh calls are made, and which line makes that happen?
Show answer
One. The first failing request sets refreshing to a pending Future in refreshOnce, and the other two requests find _refreshing non-null and await the same Future. whenComplete clears the field once the refresh finishes, so a later expiry starts a new refresh.