【发布时间】:2018-03-25 01:05:01
【问题描述】:
我无法使用 axios 捕获错误响应。怎么做? 我使用类似的东西:
axios
.post(...)
.then(response => {
console.log('Success: ', response)
}).catch(error => {
console.log('Error: ', error)
})
我看到 ajax 请求的结果有 400 个状态码,响应体看起来像 {someField:["This field may not be blank"]}(Django 后端)。没关系,我已经准备好在 catch 处理程序中处理这些错误了。
但他们改为转到成功处理程序。为什么这样?我在控制台中看到以下输出:
Success: Error: Request failed with status code 400
at createError (createError.js:16)
at settle (settle.js:18)
at XMLHttpRequest.handleLoad (xhr.js:77)
成功处理程序接收 axios 错误对象作为结果。为什么会这样,下一步该怎么做?此错误对象不包含任何有用的信息。
UPD。实际上,错误对象确实包含有用的信息,它包含在里面的响应对象。所以我们可以使用:
axios
.post(...)
.then(response => {
if (response && response.response) {
console.log('This is also an error', response.response.status)
} else {
console.log('Success: ', response)
}
}).catch(error => {
console.log('Error: ', error)
})
但这看起来超级难看。
axios版本是axios@0.16.2。
这是一个大项目,但我找不到任何 axios 自定义。
【问题讨论】:
-
我认为您正在寻找拦截器...(我正在寻找相同的,以处理 503 错误,但仍然没有弄清楚如何使其在我的代码中工作)