class XYZ {
constructor(app) {
// app is express object
this.app = app;
this.app.route('/api/url')
.get(this.wrap(this.urlhandler.bind(this)));
// to send error as json -> this never gets invoked ??
this.app.use((err, req, res, next) => {
res.status(400).json({error: err});
next(err);
});
}
// wraps each async route function to handle rejection and throw errors
wrap(fn) {
return function (req, res, next) {
Promise.resolve(fn(req, res, next)).catch(function (err) {
console.log('ERROR OCCURED: > > > > > > > ', err.code);
next(err)
});
}
}
}
Each express ASYNC route is wrapped to catch any rejection or throw error within route handler functions. Whenever there is such rejection or errors - wrap gets invoked fine and I am able to see print of "ERROR OCCURED > > > .."
However I am unable to channel that error to error handler middleware where I intend to send 400 with JSON error.
How can I fix this in above scenario ??