axios global error handling and request cancellation

Insert image description here

Both functions are implemented with an interceptor.

Summary of Foreground: Ts Simple Package axios, Unified APIs for Configuring Switch Interceptors in config

Global Error Handling

In the constructor, add a response interceptor. The benefit of registering an interceptor in the constructor is that this error interceptor is registered in the instance no matter how the encapsulation class is instantiated.

One point of attention is to request cancellation. Canceling the request causes the response promise state to be rejected, which triggers the onRejected callback of the response interceptor. Therefore, separate the request case of the request from the request error.

class HttpRequest { 
    private readonly instance: AxiosInstance;

    constructor(config: MyAxiosRequestConfig) { 
        this.instance = axios.create(config);

                // axios http Error handling(beyond 2xx scope http The status code will trigger this function)
        this.instance.interceptors.response.use(null, (error: AxiosError) => { 
            // Manually canceling the request results in“mistake”trigger
            if (error.message === "canceled") alert("Cancellation request successful");

            const {
    response } = error;
            // 1. Request timed out && Network errors are judged individually,because there's none response
            if (error.message.indexOf("timeout") !== -1) alert("Request timed out!Please try again later");
            if (error