import axios, {AxiosError} from 'axios'; import {notifier} from './util'; interface ComposedError { readonly message: string; readonly error: AxiosError; handleGlobally(): void; getError(): AxiosError; } class ComposedAjaxError implements ComposedError { name: string = 'ComposedAjaxError'; public readonly message: string; public readonly error: AxiosError; private _globallyHandled: boolean = false; constructor(error: AxiosError) { this.error = error; const statusCode = error.response ? error.response.status : null; switch (statusCode) { case 401: this.message = 'Please login to access this resource'; break; case 404: this.message = 'The requested resource does not exist or has been deleted'; break; default: this.message = 'Something went wrong and request was not completed'; } } public getError(): AxiosError { return this.error; } public handleGlobally(): void { if (this._globallyHandled) return; this._globallyHandled = true; notifier.error(this.message); }; } axios.interceptors.response.use(undefined, function (error: AxiosError) { const composedError = new ComposedAjaxError(error); return Promise.reject(composedError); }) // 1. Fetch some missing information axios.get('/api/articles/not-found').then(resp => { // So something with article information }).catch((error: ComposedError) => { const statusCode = error.getError().response ? error.getError().response.status : null; // We will handle locally // When it's a 404 error, else handle globally if (statusCode === 404) { // Do some specific error handling logic for this request // For example: show the user a paywall to upgrade their subscription in order to view achieves } else { error.handleGlobally && error.handleGlobally(); } }) // 2. Fetch some missing information axios.get('/api/users/not-found').then(resp => { // So something with user information }).catch((error: ComposedError) => { // We want to handle globally error.handleGlobally && error.handleGlobally(); })