Search⌘ K
AI Features

Global Error Handling and Interceptors with Axios

Discover how to implement Axios interceptors to manage global error handling, attach authorization tokens, and log API requests in React. This lesson helps you create a consistent and maintainable data fetching layer, improving app reliability and simplifying component code.

When apps start communicating with multiple APIs or secure endpoints, similar logic often repeats everywhere — adding tokens, logging requests, catching errors, or normalizing messages. Handling this inside each React component quickly turns messy and inconsistent. 

Interceptors

Axios provides a clean solution: interceptors — middleware-like functions that run before requests and after responses. They let us modify requests (e.g., attach headers or tokens) and globally handle errors without duplicating code across components. Combined with our Axios instance, interceptors help create a unified layer of control that makes our app more predictable and resilient.

Main concept: How interceptors work

Interceptors act like checkpoints in the request–response cycle.

apiClient.interceptors.request.use((config) => {
console.log("Request sent to:", config.url);
return config;
});
apiClient.interceptors.response.use(
(response) => response,
(error) => {
console.error("Error occurred:", error.message);
return Promise.reject(error);
}
);
Configuring Axios interceptors for request logging and error handling

We can think of them as functions that intercept outgoing and incoming network calls: ...