Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to prevent Axios from throwing an error when the response code is 500 (or not 200)?

Tags:

node.js

axios

Is there an option in axios to prevent it from throwing an error when the response code is not 200?

Currently when the user logs correctly the response code is 200. If the user login fails the response code is 500.

If axios throws an error on status code 500 my code becomes much more verbose:

this:

  var result = await axios.post(url, data, headers);
  var data = result.data;

becomes:

try {
    var result = await axios.post(url, accessOptions, headers);
    var data = result.data;
}
catch(error) {
    data = error.response.data;
}

In other words, I want to tell axios, "Don't you worry about throwing errors, let me worry about blank." Let me use try catch for syntax errors or other errors not a failed login response code 500.

like image 661
1.21 gigawatts Avatar asked Feb 03 '26 23:02

1.21 gigawatts


1 Answers

You can use the validateStatus config option:

  var result = await axios.post(url, data, {
    headers,
    // Don't throw when the status code is 500
    validateStatus: status => (status >= 200 && status < 300) || status === 500
  });
  var data = result.data;
  var result = await axios.post(url, data, {
    headers,
    // Never throw
    validateStatus: () => true
  });
  var data = result.data;
like image 118
grimsteel Avatar answered Feb 05 '26 13:02

grimsteel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!