Last active
November 11, 2019 22:04
-
-
Save Godofbrowser/d9482c93b9e7d42d987f4019827a4470 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 from 'axios'; | |
import {notifier} from './util'; | |
// errorComposer will compose a handleGlobally function | |
const errorComposer = (error) => { | |
return () => { | |
const statusCode = error.response ? error.response.status : null; | |
if (statusCode === 404) { | |
notifier.error('The requested resource does not exist or has been deleted') | |
} | |
if (statusCode === 401) { | |
notifier.error('Please login to access this resource') | |
} | |
} | |
} | |
axios.interceptors.response.use(undefined, function (error) { | |
error.handleGlobally = errorComposer(error); | |
return Promise.reject(error); | |
}) | |
// Fetch some missing information | |
axios.get('/api/articles/not-found').then(resp => { | |
// So something with article information | |
}).catch(error => { | |
const statusCode = error.response ? error.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(); | |
} | |
}) | |
// Fetch some missing information | |
axios.get('/api/users/not-found').then(resp => { | |
// So something with user information | |
}).catch(error => { | |
// 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