HTTP请求返回400,但不能抛出错误



尝试使用此请求post函数。当我用正确的requestBody运行它时,它工作得很好,但是如果requestBody无效,它返回HTTP 400并失败,但是无论我尝试抛出什么,或者像这样,catch块永远不会运行。有人能帮忙吗?这是在Node中使用请求包。

const res = async() =>
{
try
{
const res = await request({
method: "POST",
url: "url",
headers: {
"content-type": "application/json",
"authorization": "Basic " + Buffer.from(username + ":" + password).toString("base64")
},
body: JSON.stringify(requestBody)
}, function(error, response, data)
{
if(response.statusCode == 201 || response.statusCode == 200)
{
console.log(data);
}
else
{
console.log("Fell into else block!");
throw new Error("POST failed!");
}
});
}
catch (error)
{
console.log("something went wrong!", error);
}
};

由于请求函数返回承诺,请使用catch方法

const res = await request({
method: "POST",
url: "url",
headers: {
"content-type": "application/json",
"authorization": "Basic " + Buffer.from(username + ":" + password).toString("base64")
},
body: JSON.stringify(requestBody)
}, function(error, response, data)
{
if(response.statusCode == 201 || response.statusCode == 200)
{
console.log(data);
}
else
{
console.log("Fell into else block!");
throw new Error("POST failed!");
}
})
.catch((error) => {
console.log("something went wrong!", error);
});

相关内容

最新更新