1// development error handler
2// will print stacktrace
3if (app.get('env') === 'development') {
4 app.use(function (err, req, res, next) {
5 res.status(err.status || 500);
6 res.render('error.ejs', {
7 message: err.message,
8 error: err
9 });
10 });
11}
12
13// production error handler
14// no stacktraces leaked to user
15app.use(function (err, req, res, next) {
16 res.status(err.status || 500);
17 res.render('error', {
18 message: err.message,
19 error: {}
20 });
21});
22
1var router = express.Router();
2
3router.get('/req1', handleErrorAsync(async (req, res, next) => {
4 let result = await someAsyncFunction1();
5 if(result){
6 // res.send whatever
7 }
8}));
9router.post('/req2', handleErrorAsync(async (req, res, next) => {
10 let result = await someAsyncFunction2(req.body.param1);
11 if(result){
12 // res.send whatever
13 }
14}));
15router.post('/req3', handleErrorAsync(async (req, res, next) => {
16 let result = await someAsyncFunction3(req.body.param1, req.body.param2);
17 if(result){
18 // res.send whatever
19 }
20}));
21
22module.exports = router;
23
1const handleErrorAsync = func => (req, res, next) => {
2 func(req, res, next).catch((error) => next(error));
3};
4