Reputation: 92
I am having an issue with errors in express, and promisses.
I am trying to have the best way to handle errors, create a standard way to do it in my app.
However, I am in front of an issue :
validate(req.body)
.catch(e => next(new APIError(400, e)))
.then(validatedbody => searchdatabase(validatedbody))
.then(dbResult => validate(dbResult))
.catch(e => next(new APIError(500, e)))
// results from db should always be valid
.then(validatedDbResult => res.json(validatedDbResult))
If the body is wrong, we should stop and send the error, and the error will be sent using the error handling middleware, however dut to how promises work, it will also continue to the next step (searching in the DB).
What should I do ? And am I correctly handling errors in a first place ?
Thank you very much, Giltho
Upvotes: 0
Views: 199
Reputation: 665398
Just re-throw the error, and only handle it at the very end of the chain:
validate(req.body)
.catch(e => { throw new APIError(400, e); })
.then(validatedbody =>
searchdatabase(validatedbody)
.then(validate)
.catch(e => { throw new APIError(500, e); })
)
.then(validatedDbResult => res.json(validatedDbResult),
next)
Upvotes: 1