我在try/catch块中使用async/await模式发出API请求。
async myRequest(data) {
try {
await api.post('/my-endpoint/', data).then((response) => {
console.log(response.data)
});
} catch (ex) {
// WANT TO READ RESPONSE DATA HERE
}
}
如果请求成功且没有错误,我就能够使用.then()
方法读取response
。
如果请求失败,此接口将返回触发try/catch异常的422
代码。
但是,如果请求失败,此接口仍然会在响应体中返回一些我想读取但无法读取的数据,因为catch
被触发,而.then()
从未运行。
如何从catch
块内的异步函数获取响应体?
发布于 2021-09-23 02:13:59
error对象存储在ex
中,因此您可以使用} catch (ex) { console.log(ex) }
记录错误。您造成的一个问题是在调用.then
之后将其放入。当您使用try-catch块时,您不需要执行then,因为您可以将结果保存到变量中。
try-catch块的优点之一是可以处理错误,并且可以执行多个异步调用
async myRequest(data) {
try {
const response = await api.post('/my-endpoint/', data)
console.log(response.data)
} catch (ex) {
console.log(ex)
}
}
发布于 2021-09-23 03:06:34
如果要从catch块检索响应数据,可以在技术上做到这一点。
请参见以下代码。
const myRequest = async () => {
try {
const data = await fetch('https://jsonplaceholder.typicode.com/xxx/1').then((result)=> {
// You can change the status code to 422
if (result.status === 404) {
throw new Error('You can put your data here.')
// Make sure the argument you passed in Error is a string
}
return result.json()
})
} catch(e){
console.log(e.message);
}
}
myRequest()
发布于 2022-02-18 16:56:02
如果您使用的是Axios lib,请尝试以下操作:
catch (e) {
console.log(e.response.data);
}
console.log使用toString方法来格式化错误对象,因此如果只记录e(错误),就很难找到response属性。文档:https://axios-http.com/docs/handling_errors
https://stackoverflow.com/questions/69293183
复制相似问题