我有点迷失在如何使用async / await处理我的应用程序上的错误。 问题是我在userController的每个函数中都有一个try / catch来处理这个问题。 我读了许多你可以将函数包装在这样的辅助函数中的地方:
function wrapAsync(fn) {
return function(req, res, next) {
// Make sure to `.catch()` any errors and pass them along to the `next()`
// middleware in the chain, in this case the error handler.
fn(req, res, next).catch(next);
};
}
router.get('/users/:id', wrapAsync(async (req, res, next) => {
/*
if there is an error thrown in getUserFromDb, asyncMiddleware
will pass it to next() and express will handle the error;
*/
const user = await getUserFromDb({ id: req.params.id })
res.json(user);
}));
我用这种方式构建了我的NodeJS应用程序:
路线:
export class Routes {
static init(app: express.Application, router: express.Router) {
app.use('/api', router);
// Here add all the endpoints
UserRoutes.init(router);
// End of endpoints
}}
UserRoutes:
export class UserRoutes {
static init(router: express.Router) {
router
.route('/user/startVerification')
.post(UserController.startVerification);
router
.route('/user/verify')
.post(UserController.verifyUser);
router
.route('/user/register')
.put(UserController.registerUser);
}
UserController中:
export class UserController {
static async startVerification(req: any, res: express.Response) {}
static async registerUser(req: any, res: express.Response, next:
express.NextFunction) {}
static async verifyUser(req: any, res: express.Response) {}
}
我想在我的应用上应用此模式。我尝试以不同的方式使用它,但没有结果。在我的上下文中,我如何在我的路线上包装此功能?