JavaScript Catching axios request errors application wide axios catch request

In my SPA I am using axios to make requests to the API. I currently use axios request interceptors to add auth headers to requests but I also wanted to use them to catch 401 errors and remove the locally stored auth token.

I attempted to add this to the current interceptor

   axios.interceptors.response.use((response) => {
        // Set user headers only if they are not blank.
        // If DTA gets a lot of request quickly, it won't return headers for some requests
        // so you need a way to keep headers in localStorage to getting set to undefined
        if (response.headers['access-token']) {
            localStorage.setItem('access-token', response.headers['access-token'])
            localStorage.setItem('client', response.headers.client)
            localStorage.setItem('uid', response.headers.uid)
            localStorage.setItem('token-type', response.headers['token-type'])
        }

        if (response.status === 401) {
            localStorage.setItem('access-token', '')
            localStorage.setItem('client', '')
            localStorage.setItem('uid', '')
            localStorage.setItem('token-type', '')
        }
        // You have to return the response here or you won't have access to it
        // later
        return response
    })

But I found out the interceptors don't seem to run when the status returns an error code. Is there any way I can catch these errors application wide without having to add this error handling to every request manually?

Answer:1

To handle the errors from a response, you need to use the second parameter of the callback in response interceptor.

axios.interceptors.response.use((response) => {
  // Set user headers only if they are not blank.
  // If DTA gets a lot of request quickly, it won't return headers for some requests
  // so you need a way to keep headers in localStorage to getting set to undefined
  if (response.headers['access-token']) {
    localStorage.setItem('access-token', response.headers['access-token']);
    localStorage.setItem('client', response.headers.client);
    localStorage.setItem('uid', response.headers.uid);
    localStorage.setItem('token-type', response.headers['token-type']);
  }

  // You have to return the response here or you won't have access to it
  // later
  return response;
}, (error) => {
  // do what you want to do when error happens
  if (error.response.status === 401) {
    localStorage.setItem('access-token', '');
    localStorage.setItem('client', '');
    localStorage.setItem('uid', '');
    localStorage.setItem('token-type', '');
  }

  else if(error.response.status === 500) {
    // do something for all 500 errors
  } else {
    // do something for all other error codes
  }

  // should reject the promise so your api call goes to catch block
  return Promise.reject(error);
});

Refer official axios docs for more info

I have an axios interceptor library published in npm. You can refer to the source code for more details on error handling in interceptors.

axios-retry-intercceptor

Answer:2

Add second function to interceptor 'errorresponseHandler':

function errorResponseHandler(error) {

}

// apply interceptor on response
axios.interceptors.response.use(
    response => response,
    errorResponseHandler
);
Answer:3

I need regular expression to not allow only whitespaces in a field(the user should not enter just whitespaces in the field) but it can allow completely empty field and it can also allow string with ...

I need regular expression to not allow only whitespaces in a field(the user should not enter just whitespaces in the field) but it can allow completely empty field and it can also allow string with ...

  1. regular expression javascript tester
  2. regular expression javascript example
  3. regular expression javascript tutorial
  4. regular expression javascript test
  5. regular expression javascript phone number
  6. regular expression javascript mdn
  7. regular expression javascript generator
  8. regular expression javascript match
  9. regular expression javascript email
  10. regular expression javascript w
  11. regular expression javascript or
  12. regular expression javascript phone number validation
  13. regular expression javascript replace
  14. regular expression javascript space
  15. regular expression javascript validation
  16. regular expression javascript special characters
  17. regular expression javascript escape characters
  18. regular expression javascript for name
  19. regular expression javascript numbers only
  20. regular expression javascript for password

When it comes to custom extended element methods such as PlainJS closest() DOM Element method: // closest polyfill this.Element && function(ElementPrototype) { ElementPrototype.closest = ...

When it comes to custom extended element methods such as PlainJS closest() DOM Element method: // closest polyfill this.Element && function(ElementPrototype) { ElementPrototype.closest = ...

I want to be able to create a new array of objects by filtering one by multiple search terms Example: const arr = [ { 'city': 'Atlanta', 'state': 'Georgia' }, { 'city': '...

I want to be able to create a new array of objects by filtering one by multiple search terms Example: const arr = [ { 'city': 'Atlanta', 'state': 'Georgia' }, { 'city': '...

  1. filter array objects javascript
  2. filter array objects angular 6
  3. filter array objects
  4. filter array objects js
  5. filter array objects swift
  6. filter array objects jquery
  7. filter array objects angularjs
  8. filter array objects lodash
  9. filter array objects angular2
  10. array filter objects php
  11. filter array of objects by property
  12. filter array of objects typescript
  13. filter array of objects javascript es6
  14. filter array of objects by property javascript
  15. filter array of objects javascript by key
  16. filter array of objects by key
  17. filter array of objects by key value
  18. filter array of objects javascript by value
  19. filter array of objects based on property
  20. filter array of objects javascript based on property

In React, which one of the following ways is the best way to define action types? First way: Defining actions using strings like the following: const actionCreatorExample = (value) => { ...

In React, which one of the following ways is the best way to define action types? First way: Defining actions using strings like the following: const actionCreatorExample = (value) => { ...

  1. react best practices
  2. react best practices 2019
  3. react best practices 2018
  4. react best ui framework
  5. react best tutorial
  6. react best practices folder structure
  7. react best practices github
  8. react best libraries
  9. react best book
  10. react best ide
  11. react best folder structure
  12. react best css framework
  13. react best form library
  14. react best components
  15. react best course
  16. react best ui
  17. react best practises
  18. react best place to fetch data
  19. react best chart library
  20. react best router