background
let's i'm working nodejs + express. have error handlers registered express take care of errors might come in application in appropriate way(s).
as such, throw errors in application whenever need so. if there unhandled error, let propagate until reaches error handler. however, while attempting throw errors while inside of promise chain, ran problem. take following example:
function find() { // consider promise library such bluebird return new promise(function (resolve, reject) { // ... logic ... }); } function controller (req, res) { // ... omitted ... find().then(function (result)) { if (result) { // let 'res' express response object res.send("it exists!"); } else { // let specificerror prototypical subclass of error throw new specificerror("couldn't find it."); } }).catch(function (error) { // throw error again, error handler can finish // job throw error; }); }
whereas have been expecting error re-throwing hit @ least generic error handler, instead seeing requests send application hang, , promise library using complain of unhandled rejection
.
question
quite simply, wondering how resolve fact appear mishandling rejection creating throwing error in promise chain.
edit: clarification (specifically) error handler , controller
function are, see comments below.
assuming have bound function like
app.get('/', controller);
when express calls controller
, has yielded 100% control you. if exception thrown synchronously controller
, express nice , treat error you. invoke asynchronous code however, responsibility decide how handle errors.
in case of express, have 2 options:
- since passed
req
,res
, can catch error , send whatever response want user. controller
has function signature offunction(req, res, next)
in express. common format.
the next
callback expects called if have not written in response yet. if call next()
no arguments, tells express keep processing set of url handlers has, trying find 1 handle request, returning 404 if none found.
if however, pass argument next
next(err)
, express skip on remaining url handlers, instead looking error handlers. express allows register custom handlers, if none found, return 500.
so should in example? want like
function controller (req, res, next) { find().then(function (result)) { if (!result) throw new specificerror("couldn't find it."); res.send("it exists!"); }).catch(next); }
that means if exception thrown inside of promise chain, next
function called it, , express take on there.
Comments
Post a Comment