Hi, i'm new in node and express.I have a route handler that may call different functions depending on some request parameters, and I would like to know what's the best way to deal with errors inside the functions in order to pass errors to the error handling middleware.Consider something like this:router.get('/error/:error_id', (req, res, next) => { my_function(); } function my_function(){ // do something async, like readfile var f = fs.readFile("blablabla", function (err, data) { // would want to deal with the error }); } If an error occurs during fs.readFile, how do I pass the error to next to forward it to the error middleware?In case the function didn't call any async I/O operation, a simple try/catch in the route handler would be ok (i suppose), like this:router.get('/error/:error_id', (req, res, next) => { try{ my_function(); } catch(e){ next(e); }; } function my_function(){ // do stuff var f = fs.readFileSync("blablabla"); // possibly throws an error } Cheers
Submitted April 07, 2017 at 02:29PM by honestserpent
No comments:
Post a Comment