aso*_*rov 0 javascript error-handling express typescript
我希望块内抛出的特定错误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,
};
}
};
Run Code Online (Sandbox Code Playgroud)
之后中间件处理错误。
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,
});
};
Run Code Online (Sandbox Code Playgroud)
如果您在 -block 中抛出错误try,catch则会捕获它。您能做的最好的事情就是检查catch-block 是否抛出了您不想捕获的错误,如果是,则重新抛出它。
const someFunc = async () => {
try {
throw {
status: 404,
message: "Not Found",
};
} catch (error) {
// If a 404 error is caught, rethrow it.
if (error.status === 404) {
throw error;
}
throw {
status: 500,
message: "Something went wrong",
reason: error,
};
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
969 次 |
| 最近记录: |