简体   繁体   中英

Axios override, get status code from the data response instead of status

I'm calling an API that defines the statusCode from data instead of the response code:

{
  data: {
     statusCode: 422,
     message: "User's not found"
  }, 
 status: 200
}

In my axios get request it's getting the status code from the status instead in data.

return axios.get(`${process.env.BASE_URL}/users`)
      .then(response => {
        console.log(response);
      }).catch(err => {
        console.log(err.message);
      });

I'm getting the response but it should go to catch since it's 422.

How can I refer to the statusCode of the data response so that if it's not 200 it should go to catch statement

You can handle with standard if statement inside the .then()

return axios.get(`${process.env.BASE_URL}/users`)
      .then(response => {
        if(response.data.statusCode===442){
           ...//custom error handling goes here
        }else{
           ...//if statusCode is a success one
        }      
      }).catch(err => {
        console.log(err.message);
      });

You can intercept the response, inspect the data and throw a custom error in this case:

// Add a response interceptor
axios.interceptors.response.use(function(response) {
    if (response.data && response.data.statusCode && !(response.data.statusCode >= 200 && response.data.statusCode < 300)) throw new Error()
    return response;
}, function(error) {
    return Promise.reject(error);
});

// Make a GET request
axios.get(url)
    .then((data) => {
        console.log('data', data)
    })
    .catch((e) => {
        console.log('error', e)
    })

This way you configure your axios instance so you dont have to repeat yourself for every single request in your app

Also, you can override the status using following code. But since status validation has already executed, it will not throw errors on bad status codes

// Add a response interceptor
axios.interceptors.response.use(function(response) {
    if (response.data && response.data.statusCode) response.status = response.data.statusCode
    return response;
}, function(error) {
    return Promise.reject(error);
});

Check the response.data.statusCode value, if it is 442 then you should ideally throw an Error and let it be handled in the .catch callback.

return axios.get(`${process.env.BASE_URL}/users`)
      .then(response => {
        if(response.data.statusCode===442){
           throw new Error(response.data.message); //using throw instead of Promise.reject() to break the control flow. 
        }else{
           //return the data wrapped in promise
        }      
      })
      .catch((err) => {
          console.log(err.message);
          return Promise.reject(err.message);
      });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM