← Back

HTTP Error Handler Context Binding: Fixing "this is undefined" in Axios Interceptors

·frontend-explore

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

  1. Arrow Functions for Callbacks: Preserve this context automatically
  2. Bind in Constructor: Alternative if you need regular functions
  3. TypeScript Helps: Strict mode catches some context issues
  4. Test Interceptors: Easy to miss in unit tests
  5. Class Properties: Arrow function properties auto-bind