createErrorInterceptor function

InterceptorsWrapper createErrorInterceptor({
  1. ErrorMessageConfig? config,
  2. void onError(
    1. NetworkException
    )?,
})

简化的错误拦截器创建方法

Implementation

InterceptorsWrapper createErrorInterceptor({
  ErrorMessageConfig? config,
  void Function(NetworkException)? onError,
}) {
  return InterceptorsWrapper(
    onError: (err, handler) {
      final networkException = ExceptionConverter.fromDioError(err);

      // 创建自定义消息的异常
      String finalMessage = networkException.message;
      final customMessage = config?.getMessage(networkException.type);
      if (customMessage != null) {
        finalMessage = customMessage;
      }

      // 如果是HTTP错误,尝试使用自定义HTTP消息
      if (networkException.statusCode != null) {
        final httpMessage = config?.getHttpMessage(
          networkException.statusCode!,
        );
        if (httpMessage != null) {
          finalMessage = httpMessage;
        }
      }

      // 创建更新后的异常
      final updatedException = NetworkException(
        type: networkException.type,
        message: finalMessage,
        statusCode: networkException.statusCode,
        endpoint: networkException.endpoint,
        originalError: networkException.originalError,
      );

      onError?.call(updatedException);

      handler.next(err);
    },
  );
}