Intercept Axios errors
17 March 2022 (Updated 18 March 2022)
Let’s suppose you want to deal with 401 Unauthorized
status codes by redirecting the user to the login screen. You can use an approach like this:
import axios, { AxiosError, AxiosInstance, AxiosRequestConfig } from 'axios'
import authService from './services/authService'
const apiClient: AxiosInstance = axios.create({
baseURL: 'http://localhost:8080',
})
apiClient.interceptors.request.use(addAuthorizationHeader)
apiClient.interceptors.response.use(undefined, handleError)
function addAuthorizationHeader(
config: AxiosRequestConfig
): AxiosRequestConfig {
if (authService.isAuthenticated()) {
config.headers['Authorization'] = `Bearer ${authService.getToken()}`
}
return config
}
function handleError(error: AxiosError) {
const response = error.response?.data
// Wasn't able to get any response at all. Perhaps because of network errors.
if (!response) {
return Promise.reject(error)
}
if (
response.code === 'UNAUTHENTICATED' &&
response.message === 'Invalid token'
) {
return authService.logout()
}
return Promise.reject(error)
}
export default apiClient
Sources
Tagged:
JavaScript tooling
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment