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

huangapple go评论56阅读模式
英文:

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

问题

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.

英文:

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.

答案1

得分: 4

你可以使用validateStatus配置选项

  var result = await axios.post(url, data, {
    headers,
    // 当状态码为500时不抛出错误
    validateStatus: status => (status >= 200 && status < 300) || status === 500
  });
  var data = result.data;
  var result = await axios.post(url, data, {
    headers,
    // 永远不抛出错误
    validateStatus: () => true
  });
  var data = result.data;
英文:

You can use the validateStatus config option:

  var result = await axios.post(url, data, {
    headers,
    // Don&#39;t throw when the status code is 500
    validateStatus: status =&gt; (status &gt;= 200 &amp;&amp; status &lt; 300) || status === 500
  });
  var data = result.data;
  var result = await axios.post(url, data, {
    headers,
    // Never throw
    validateStatus: () =&gt; true
  });
  var data = result.data;

huangapple
  • 本文由 发表于 2023年5月13日 11:43:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76240972.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定