【发布时间】:2022-01-25 07:40:45
【问题描述】:
我希望try 块内抛出的特定错误不由catch(err) 处理
例子:
const someFunc = async () => {
...
try {
...
// This error should not be handled by the catch and go straight to the middleware
throw {
status: 404,
message: "Not Found",
};
} catch (error) {
throw {
status: 500,
message: "Something went wrong",
reason: error,
};
}
};
然后中间件处理错误。
export const errorHandler: ErrorRequestHandler = (err, req, res, next) => {
const { status = 500, message, reason } = err;
res.status(status).json({
success: false,
message: message || "Something went wrong",
reason: reason || undefined,
});
};
【问题讨论】:
-
不太可能,我不认为。您可以创建一个自定义错误函数,将错误传递给您的中间件,但您不能直接在 try catch 块中抛出而不被捕获。
-
您可以实现多个 catch 块来处理不同类型的错误。见:Conditional catch-blocks
-
没有什么要求你抛出
Error的实例,但你应该在你的代码中。请参阅有关错误处理的快速文档:expressjs.com/en/guide/error-handling.html
标签: javascript typescript express error-handling