异步等待 http 请求错误捕获未定义
async await http request error catch is undefined
我正在 async/await 使用 axios http 调用:
try{
let result = await axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
}catch(err){
// err is undefined if hit with http request error
console.log(err.response.status) // undefined
}
但是当我遇到请求错误时,出现未定义错误,为什么?
我正在尝试获取 err.response.status
和 err.response.data.error
最重要的是..你没有在 "try" 块内返回或执行任何东西..而且你没有 "then" 块。为了获得成功或错误,你必须从 try 块中删除 "result" 变量......下面有两个你可以尝试的 axios 示例,它们会起作用......
- 第一个例子..(完整的 axios 方法和工作方法)
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
- 第二个示例(带 try 和 catch 块的公理)
try{
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
});
}
catch(err){
console.log(err);
}
- 但是您不需要使用第二个示例,因为第一个示例本身可以用作 try 和 catch 块。在我看来,您应该选择第一个选项。(效率更高)。希望这会帮助你..快乐编码 B)
我正在 async/await 使用 axios http 调用:
try{
let result = await axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
}catch(err){
// err is undefined if hit with http request error
console.log(err.response.status) // undefined
}
但是当我遇到请求错误时,出现未定义错误,为什么?
我正在尝试获取 err.response.status
和 err.response.data.error
最重要的是..你没有在 "try" 块内返回或执行任何东西..而且你没有 "then" 块。为了获得成功或错误,你必须从 try 块中删除 "result" 变量......下面有两个你可以尝试的 axios 示例,它们会起作用......
- 第一个例子..(完整的 axios 方法和工作方法)
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
- 第二个示例(带 try 和 catch 块的公理)
try{ axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }); } catch(err){ console.log(err); }
- 但是您不需要使用第二个示例,因为第一个示例本身可以用作 try 和 catch 块。在我看来,您应该选择第一个选项。(效率更高)。希望这会帮助你..快乐编码 B)