Thursday 18 May 2017

Express: how to handle errors into a route handler that uses promises?

I'm trying to understand what's the best way to handle errors in express.I have a route handler that does some sync computations in the beginning, and after it is done searches the DB. After the DB returns, some more computation is needed.It's a very common sequence of actions so i'm sure you all did it.I have implemented the DB search using the promise flavour instead of using callbacks.I want to understand how to properly handle errors depending on where I need to raise/throw errors.So, here is the pseudo-cod, please check the comments for clarification of my question:router.post('/test', function(req,res,next){ // some sync computation, eg. read headers let header1 = null; try{ req.headers['header1']; }catch(err){ return throw(new Error('header not found')); // is this ok here? } db.find({ where: { id: header1 } }).then((data)=>{ // do some computation with data data.value1 += 1; // if an error occurs here, or I want to generate an error on purpose, how should I handle it? // 1. throw new Error('blabla')? -> will go to the catch where maybe I can return next(err) // 2. return next(new Error('blabla'))? }).catch((err)=>{ return next(err); }); } I hope my question makes sense.tldr: if an error happens or I want to raise an error into the .then function of a promise, should I directly return it there thought return next(err), or throw the error to pass the handling to the .catch method?

Submitted May 18, 2017 at 08:23AM by honestserpent

No comments:

Post a Comment