Created
October 10, 2022 14:18
-
-
Save Guifgr/be5cab3251af8fc77045be9492165609 to your computer and use it in GitHub Desktop.
intercept errors react axios
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 { getToken, logout } from './auth' | |
import config from '../Constants' | |
export const hub = config.url.Hub | |
const api = axios.create({ | |
baseURL: config.url.route, | |
}) | |
api.interceptors.request.use(async config => { | |
const token = getToken() | |
if (token) { | |
config.headers.Authorization = `Bearer ${token}` | |
} | |
return config | |
}) | |
api.interceptors.response.use( | |
function (response) { | |
return response | |
}, | |
function (error) { | |
if (error.message === 'Request failed with status code 401') logout() | |
if (error.message === 'Request failed with status code 452') logout() | |
if (error.message === 'Request failed with status code 500') | |
window.location.href = '#/#/servererror' | |
return Promise.reject(error) | |
}, | |
) | |
export default api | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment