Skip to content

Instantly share code, notes, and snippets.

@guamacherox
Last active April 8, 2023 14:46
Show Gist options
  • Save guamacherox/d9658bdf1d38c65141beb62c5d9752c1 to your computer and use it in GitHub Desktop.
Save guamacherox/d9658bdf1d38c65141beb62c5d9752c1 to your computer and use it in GitHub Desktop.
React Hook for axios error interceptor
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;
@vresetnikov
Copy link

Hello, how would you plug it in?

@kazem3d
Copy link

kazem3d commented Jan 29, 2023

did you find out how to plug it in?

@n-lavrenko
Copy link

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