error.ts 2.37 KB
import { reportNetworkError } from './sentry';

/**
 * 请求错误类
 */
export class RequestError extends Error {
  code: string;
  config: any;
  request?: any;
  response?: any;
  isRequestError: boolean;

  constructor(message: string, code: string, config: any, request?: any, response?: any) {
    super(message);
    this.name = 'RequestError';
    this.code = code;
    this.config = config;
    this.request = request;
    this.response = response;
    this.isRequestError = true;

    // 确保instanceof正常工作
    Object.setPrototypeOf(this, RequestError.prototype);
    
    // 如果配置中包含 sentryDsn,则上报错误到 Sentry
    if (config && config.sentryDsn) {
      this.reportToSentry();
    }
  }
  
  /**
   * 将错误上报到 Sentry
   */
  reportToSentry(): void {
    const errorInfo = {
      code: this.code,
      url: this.config?.url,
      method: this.config?.method,
      params: this.config?.params,
      status: this.response?.status,
      statusText: this.response?.statusText,
      responseData: this.response?.data
    };
    
    reportNetworkError(this.message, errorInfo);
  }

  /**
   * 创建网络错误
   */
  static createNetworkError(message: string, config: any, request?: any): RequestError {
    const error = new RequestError(
      message || '网络错误',
      'NETWORK_ERROR',
      config,
      request
    );
    return error;
  }

  /**
   * 创建超时错误
   */
  static createTimeoutError(config: any, request?: any): RequestError {
    return new RequestError(
      `请求超时: 超过了${config.timeout}ms`,
      'TIMEOUT_ERROR',
      config,
      request
    );
  }

  /**
   * 创建取消错误
   */
  static createCancelError(config: any, request?: any): RequestError {
    return new RequestError(
      '请求已被取消',
      'CANCEL_ERROR',
      config,
      request
    );
  }

  /**
   * 创建服务器错误
   */
  static createServerError(message: string, config: any, request?: any, response?: any): RequestError {
    return new RequestError(
      message || '服务器错误',
      'SERVER_ERROR',
      config,
      request,
      response
    );
  }

  /**
   * 创建请求错误
   */
  static createRequestError(message: string, config: any, code = 'REQUEST_ERROR', request?: any): RequestError {
    return new RequestError(
      message,
      code,
      config,
      request
    );
  }
}