onError method

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

Called when an exception was occurred during the request.

Implementation

@override
void onError(DioException err, ErrorInterceptorHandler handler) {
  final Object? mapped = err.error;

  final bool shouldReport = switch (mapped) {
    // Expected / non-actionable:
    RequestCancelledException _ => false,
    ValidationException _ => false,
    UnauthorizedException _ => false,
    ForbiddenException _ => false,
    NotFoundException _ => false,
    ConflictException _ => false,

    // Actionable / useful to track:
    NetworkException _ => true,
    TimeoutException _ => true,
    CertificatePinningException _ => true,

    // Unknown/unmapped exceptions:
    _ => true,
  };

  final Map<String, Object?> extras = <String, Object?>{
    'dio.method': err.requestOptions.method,
    'dio.path': err.requestOptions.path,
    'dio.baseUrl': err.requestOptions.baseUrl,
    'dio.type': err.type.toString(),
    'http.status': err.response?.statusCode ?? -1,
  };

  if (shouldReport) {
    _logger.error('[Dio] Actionable network error', error: err, stackTrace: err.stackTrace, extras: extras);
  } else {
    _logger.warn('[Dio] Request failed', error: null, stackTrace: null, extras: extras, escalate: false);
  }

  handler.next(err);
}