如何获得状态代码为400的响应api



我使用api,当api返回200状态码时,我返回响应,但当api返回400状态码时api返回带有错误的数组,我的问题是如何获取此数组错误并返回此数组。

代码

try {
const config = {
method: 'get',
url: 'http://localhost:4000/api/orders',
headers: {'Key': '96db259b-2239-4abb-9b9d-a682a1de6b3c'}
}
const result = await axios(config)
return result.data
} catch (error) {
console.log('error ' + error)
returns result.data.errors
}

这是状态代码为400的响应。

"errors": [
{
"value": "96db259b-2239-4abb-9b9d-a682ssa1de6b3c",
"msg": "the API key 96db259b-2239-4abb-9b9d-a682ssa1de6b3c is invalid",
"param": "key",
"location": "headers"
}
]

你可以这样做

try {
const config = {
method: 'get',
url: 'http://localhost:4000/api/orders',
headers: {'Key': '96db259b-2239-4abb-9b9d-a682a1de6b3c'}
}
const result = await axios(config)
if(result.status != 200) {
throw new Error(`[Status ${result.status}] Something went wrong `);
}
return result.data
} catch (error) {
console.log('error ' + error)
returns error.message;
}

只需要调用错误的消息属性,例如:

try {
const config = {
method: 'get',
url: 'http://localhost:4000/api/orders',
headers: {'Key': '96db259b-2239-4abb-9b9d-a682a1de6b3c'}
}
const result = await axios(config)
return result.data // this only called with success response, status code 200
} catch (error) {
console.log('error ' + error)
returns error.message;
}

最新更新