我无法弄清楚如何从生成的错误中正确发送Express路由器处理程序响应并在嵌套的try / catch块中捕获。
在下面的代码中,如果内部Try / Catch 3块捕获错误,我希望路由处理程序的所有执行都停止,这将返回状态404错误。此时,当Try / Catch 3中捕获到错误时,路由处理程序继续执行代码块A中的后续代码,捕获并返回Try / Catch 1中的状态400错误。然后路由hanlder发送此400状态响应。如何让路由处理程序返回Try / Catch Block 3 404响应,因此永远不会执行代码块A中的代码?
我已经尝试在各个地方修改return语句,但似乎无法让路由处理程序单独返回内部Try / Catch 3中捕获的错误。任何人都可以相对轻松地看到我在哪里未能正确返回或管理错误传播?
app.get("/endpoint/url", async(req, res) => {
// Try/Catch 1
try {
// Define an async function
const queryApiFunc = async() => {
// Try/Catch 3
try {
let results = await axios({
// Axios Query to API
})
if (/*condition is met*/)
throw "No results found";
}
catch (e) {
if (e === "No results found") {
res.statusMessage = e;
return res.status(404).end();;
}
}
}
// Try/Catch 2
try {
// Call the defined async function
await queryApiFunc();
} catch (e) {
return e;
}
// Code Block A
// contains another async call to API
// generates 400 status error
// Code Block A
} catch (e) {
return e;
}
}
看起来似乎正在发生,因为你实际上并没有从函数中抛出任何东西。我不完全确定你要完成的是什么,但是结构更像下面的内容呢?
app.get("/endpoint/url", async(req, res) => {
const queryApiFunc = async() => {
let results = await axios({
});
if (/*condition is met*/) throw "No results found";
};
try {
await queryApiFunc();
//Code Block A
} catch (e) {
if (e === "No results found") {
res.statusMessage = e;
return res.status(404).end();;
}
}
});
这应该摆脱一些try / catch陷阱,你有吞咽错误的风险,然后让你达到实际的预期结果。