[英]How to catch all errors in route as a middleware in ExpressJS?
I have a problem and I haven't found a solution yet.我有一个问题,我还没有找到解决方案。 I want to catch all errors if occur any error in each route but it's very inconvenient when I have to do it many times.
如果在每条路线中发生任何错误,我想捕获所有错误,但是当我必须多次这样做时非常不方便。
How can i implement it as a middleware same like app.use(ErrorHandle);
我如何将它实现为与
app.use(ErrorHandle);
? ?
Code in ErrorHandler.js: ErrorHandler.js 中的代码:
export const ErrorHandler = func => async (req, res, next) => {
try {
await func(req, res, next);
} catch (error) {
next(error);
}
}
Code in index.js index.js 中的代码
app.use((err, req, res, next) => {
if (err) {
return res.status(err.statusCode || 500).json(err.message);
}
next()
});
Code in route need to catch error:路由中的代码需要捕获错误:
import { ErrorHandler } from './ErrorHandler';
export const uploadMedia = ErrorHandler(async (req, res) => {
// do something...
let error = new Error();
error.statusCode = 404;
error.message = 'Content not found!';
}
Sorry if misunderstood your question... When you do the code below which you provided, you are assuming that if an error reaches the end of the stack via next(err)
, such handler should be called.抱歉,如果误解了您的问题...当您执行下面提供的代码时,您假设如果错误通过
next(err)
到达堆栈末尾,则应调用此类处理程序。 Hence it's the last declaration after all your routes.因此,这是您所有路线之后的最后一个声明。
app.use((err, req, res, next) => {
if (err) {
return res.status(err.statusCode || 500).json(err.message);
}
next()
});
That, however, won't catch unhandledExceptionErrors
.但是,这不会捕获
unhandledExceptionErrors
。 You still need the good old你仍然需要美好的旧时光
try {
// throw error somewhere
} catch (e) {
next(e);
}
Personally, I haven't tried this package but it seems so be a nice hack for Express router's inability to handle promise returns.就个人而言,我还没有尝试过这个 package ,但它似乎是 Express 路由器无法处理 promise 返回的一个很好的破解。 About express-promise-router:
关于 express-promise-router:
A simple wrapper for Express 4's Router that allows middleware to return promises.
Express 4 路由器的简单包装器,允许中间件返回承诺。 This package makes it simpler to write route handlers for Express when dealing with promises by reducing duplicate code.
package 通过减少重复代码,在处理 Promise 时为 Express 编写路由处理程序变得更加简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.