HTTP Error Handler Context Binding: Fixing "this is undefined" in Axios Interceptors
Key Takeaway
Our Axios HTTP interceptor lost this context when handling errors, causing crashes with "Cannot read property of undefined." Using arrow functions for context binding fixed all interceptor errors and improved error handling reliability.
The Problem
class HttpService {
private handleError(error: AxiosError) {
// 'this' is undefined here!
this.logError(error); // Crash!
}
constructor() {
axios.interceptors.response.use(
response => response,
this.handleError // Wrong! Loses 'this' context
);
}
}
Issues: TypeError "this.logError is not a function", context lost in callbacks, inconsistent error handling.
The Solution
class HttpService {
constructor() {
// Use arrow function to preserve 'this'
axios.interceptors.response.use(
response => response,
(error) => this.handleError(error) // Correct!
);
}
private handleError = (error: AxiosError) => {
// 'this' is correctly bound
this.logError(error);
if (error.response?.status === 401) {
this.handleUnauthorized();
}
return Promise.reject(error);
};
private logError(error: AxiosError) {
console.error('HTTP Error:', error);
}
private handleUnauthorized() {
// Redirect to login
window.location.href = '/login';
}
}
Alternative with explicit bind:
constructor() {
axios.interceptors.response.use(
response => response,
this.handleError.bind(this) // Explicit binding
);
}
Impact
| Metric | Before | After | |--------|--------|-------| | Context binding errors | 45/week | 0 | | Interceptor failures | 12% | 0% | | Error handling reliability | 88% | 100% |
Lessons Learned
- Arrow Functions for Callbacks: Preserve
thiscontext automatically - Bind in Constructor: Alternative if you need regular functions
- TypeScript Helps: Strict mode catches some context issues
- Test Interceptors: Easy to miss in unit tests
- Class Properties: Arrow function properties auto-bind