/**
 * API异常模块
 * @date 2022-03
 * @author 何华东
 */

import { AxiosError, AxiosResponse } from 'axios';

/**
 * API异常
 */
export default class ApiError extends Error {
    constructor() {
        super();
        this.name = this.constructor.name;
    }

    /**
     * 请求地址
     */
    requestUrl: string;

    /**
     * 请求头
     */
    requesHeaders?: any;

    /**
     * 请求数据
     */
    requestData?: any;

    /**
     * 错误码,对应axiosError.code
     * 
     * ECONNABORTED 为请求超时时
     */
    code?: string;

    /**
     * http状态码，例如：200、500、404
     */
    statusCode?: any;

    /**
     * 响应
     */
    response?: any;
}

/**
 * 从axiosError生成一个ApiError异常对象
 */
export function generateApiErrorFromAxiosError(axiosError: AxiosError) {
    let apiError = new ApiError();

    apiError.name = axiosError.name;
    apiError.message = axiosError.message;
    apiError.requestUrl = axiosError.config.url?.startsWith('http') ? axiosError.config.url : (axiosError.config.baseURL + (axiosError.config.url || ''));
    apiError.requesHeaders = axiosError.config.headers;
    apiError.requestData = axiosError.config.data;
    apiError.code = axiosError.code;
    apiError.statusCode = axiosError.response?.status;
    apiError.response = axiosError.response?.data;

    return apiError;
}

/**
 * 从axiosResponse生成一个ApiError异常对象
 * @param message 错误信息
 */
export function generateApiErrorFromAxiosResponse(axiosResponse: AxiosResponse, message?: string) {
    let apiError = new ApiError();

    apiError.message = message;
    apiError.requestUrl = axiosResponse.config.url?.startsWith('http') ? axiosResponse.config.url : (axiosResponse.config.baseURL + (axiosResponse.config.url || ''));
    apiError.requesHeaders = axiosResponse.config.headers;
    apiError.requestData = axiosResponse.config.data;
    apiError.statusCode = axiosResponse.status;
    apiError.response = axiosResponse.data;

    return apiError;
}

/**
 * 从axiosError抛出ApiError异常
 */
export function throwApiErrorFromAxiosError(axiosError: AxiosError) {
    throw generateApiErrorFromAxiosError(axiosError);
}

/**
 * 从axiosResponse抛出ApiError异常
 * @param message 错误信息
 */
export function throwApiErrorFromAxiosResponse(axiosResponse: AxiosResponse, message?: string) {
    throw generateApiErrorFromAxiosResponse(axiosResponse);
}