Last active
November 11, 2019 22:04
-
-
Save Godofbrowser/cb7da7cb7f7b5e8430c607e0653059cb to your computer and use it in GitHub Desktop.
This gist is part of an article and may not covey the actual message on it's own. Link to article: https://medium.com/@ejjay/a-short-ajax-story-on-error-handlers-8baeeccbc062
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment