onError method
- @override
override
The callback will be executed on error.
If you want to resolve the request with some custom data,
you can return a Response object or return dio.resolve
.
If you want to continue the request, return the DioError object.
Implementation
@override
onError(DioError err) async {
_dio.interceptors.errorLock.lock();
if (_isNotRetryable(err)) {
_dio.interceptors.errorLock.unlock();
return err;
}
try {
_dio.interceptors.requestLock.lock();
RequestOptions options = err.response.request;
final token = await _tokenStore.fromStore();
if (err.request.headers["Authorization"] !=
"Bearer ${token.accessToken}") {
// tokens were refreshed by another API request.
print(
"just retry ${options.path} since access token was already refreshed by another request.");
return _dio.request(options.path, options: options);
}
final tokenResponse =
await _kauthApi.refreshAccessToken(token.refreshToken);
await _tokenStore.toStore(tokenResponse);
print("retry ${options.path} after refreshing access token.");
return _dio.request(options.path, options: options);
} catch (e) {
if (e is KakaoAuthException ||
e is KakaoApiException && e.code == ApiErrorCause.INVALID_TOKEN) {
await _tokenStore.clear();
}
return err;
} finally {
_dio.interceptors.requestLock.unlock();
_dio.interceptors.errorLock.unlock();
}
}