onError method

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

Intercepts any errors that occur when making an HTTP request using Dio.

This method logs error details using the Infospect system.

  • error: The error details.
  • handler: An error interceptor handler, which determines how the error should be handled.

Implementation

@override
void onError(DioException error, ErrorInterceptorHandler handler) {
  try {
    InfospectNetworkResponse httpResponse = InfospectNetworkResponse();
    dynamic body = '';
    int size = 0;
    int? status;
    final err = error.toString();
    StackTrace? st;
    if (error is Error) {
      final basicError = error as Error;
      st = basicError.stackTrace;
    }

    infospect.addError(InfospectNetworkError(error: err, stackTrace: st),
        error.requestOptions.hashCode);

    if (error.response == null) {
      status = -1;
      infospect.addResponse(httpResponse, error.requestOptions.hashCode);
    } else {
      status = error.response!.statusCode;

      if (error.response!.data != null) {
        body = error.response!.data;
        size = utf8.encode(error.response!.data.toString()).length;
      }
      final Map<String, String> headers = {};
      error.response!.headers.forEach((header, values) {
        headers[header] = values.toString();
      });

      infospect.addResponse(
        httpResponse.copyWith(
          headers: headers,
          body: body,
          size: size,
          status: status,
        ),
        error.response!.requestOptions.hashCode,
      );
    }
  } catch (e, st) {
    infospect.addLog(
      InfospectLog(
        message: e.toString(),
        stackTrace: st,
        error: e,
        level: DiagnosticLevel.error,
      ),
    );
  }
  handler.next(error);
}