Last active
April 8, 2023 14:46
-
-
Save guamacherox/d9658bdf1d38c65141beb62c5d9752c1 to your computer and use it in GitHub Desktop.
React Hook for axios error interceptor
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 { useEffect } from 'react'; | |
import axios from 'axios'; | |
/** | |
* @description Hooks an axios error interceptor for your react application | |
*/ | |
const useErrorHandler = () => { | |
const errorInterceptor = axios.interceptors.response.use( | |
res => res, | |
error => { | |
if (error?.response?.status) { | |
switch (error.response.status) { | |
case 401: | |
// Actions for Error 401 | |
throw error; | |
case 500: | |
// Actions for Error 500 | |
throw error; | |
default: | |
console.error('from hook interceptor => ', error); | |
throw error; | |
} | |
} else { // Occurs for axios error.message = 'Network Error' | |
throw error; | |
} | |
} | |
); | |
useEffect(() => { | |
return () => { | |
axios.interceptors.response.eject(errorInterceptor); | |
}; | |
}); | |
}; | |
export default useErrorHandler; |
did you find out how to plug it in?
Yeah, is't a door without a wall 🤣
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
did you find out how to plug it in?