英文:
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'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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论