How can I convert a rejected promise to an exception and throw it out of the Express route handler?
In one of my application's route handlers, I call a method that returns the promise Q. Instead of handling the rejection with the method .catch
, I want it to be thrown and caught in my error handler for all Express applications.
I tried method Q done
, but it throws the exception asynchronously, so instead of handling my catch-all error handler, it propagates to the end and my application ends:
// The route handler
function index(req, res) {
dao.findById(id).then(function (data) {
res.send(data);
}).done();
}
// The catch all event-handler
function catchAllErrorHandler(err, req, res, next) {
console.log(err, req, res);
}
// Registration of the catch-all event handler
app.use(catchAllErrorHandler);
The error never goes into the catch error handler. Is there a way to get handled errors to be handled with catchAllErrorHandler
?
source to share
This does not answer your question directly, but rather shows another way to achieve your goal.
Each intermediate code handler in an expression is signed (request, response, next)
. Your function is index
currently not further defined.
When you call next with an argument, express considers the argument to be an error and controls it accordingly.
So, in your case, change your function index
to include the following parameter, and change .done()
to .catch(next)
which is called next to any error that occurs and allows express to handle it.
dao.findById(id)
// Handle success
.then(function (data) {
res.send(data);
})
// Handle failure
.catch(next);
source to share
I tried Q done method
You are most likely best off getting exceptions from promises.
but it throws an exception asynchronously
Of course it is, promises are always asynchronous. You cannot determine if your promise will reject in the future and throw an exception synchronously ...
Is there a way to get handled errors to be handled with
catchAllErrorHandler
?
Pass the handler explicitly as a handler:
dao.findById(id).then(function (data) {
res.send(data);
}).catch(catchAllErrorHandler);
Alternatively, since Q v1.3 you can use raw variance tracking and post there catchAllErrorHandler
.
source to share