Axios Exception Interceptor - Some request custom handling exceptions Author: Chuwen Time: 2023-02-24 Classification: TypeScript ##Current situation Current 'request. ts' of the project: ```ts import toast from "./toast" const request = axios.create({ baseURL: " https://api.nowtime.cc ", responseType: "json", timeout: 12_000 }) //Response interceptor request.interceptors.response.use( response => { //TODO response interceptor related operations return response }, error => { //Handling network errors if ( error.code === "ECONNABORTED" || error.message === "Network Error" || error.message.includes("timeout") ) { toast("Network timeout", 5e3, true) return Promise.reject(error) } if (error.response) { //TODO processing API response error const { status } = error.response if (status === 500) { toast("Server error", 5e3) } // ...... } return Promise.reject(error) } ) export default request ``` However, there are some drawbacks in the above code. For example, if there are some requests that need custom exception handling, and 'toast' does not need to pop up, then we need to do so ##Implementation code Add the 'axios. ts' file and paste the following code: ```ts import "axios" declare module "axios" { //Extension of AxiosRequestConfig interface export interface AxiosRequestConfig { catchHandler?: boolean;// Whether to enable automatic exception handling } } ``` `request.ts`: ```ts import toast from "./toast" const request = axios.create({ baseURL: " https://api.nowtime.cc ", responseType: "json", timeout: 12_000 }) //Response interceptor request.interceptors.response.use( response => { //TODO response interceptor related operations return response }, error => { //Handling network errors if ( error.code === "ECONNABORTED" || error.message === "Network Error" || error.message.includes("timeout") ) { toast("Network timeout", 5e3, true) return Promise.reject(error) } //Judge whether the current request config processes the same exception //False: Do not handle the same error if (Object.hasOwn(error.config, "catchHandler") && error.config.catchHandler === false) { return Promise.reject(error) } if (error.response) { //TODO processing API response error const { status } = error.response if (status === 500) { toast("Server error", 5e3) } // ...... } return Promise.reject(error) } ) export default request ``` ###Use: ```ts import request from "./request" rquest.get(`/v2/user`, { catchHandler: true }) ``` label: TypeScript , Axios