node.js - How do I handle errors in a function called from a route handler in Express, NodeJS? -
this may extremely stupid, haven't found because don't understand how should search this.
i have route handler may call different functions depending on request parameters, , know what's best way deal errors inside functions in order pass errors error handling middleware. consider this:
router.get('/error/:error_id', (req, res, next) => { my_function(); } function my_function(){ // async, readfile var f = fs.readfile("blablabla", function (err, data) { // want deal error }); } if error occurs during fs.readfile, how pass error next forward error middleware? solution pass next param function function my_function(next){...}?
in case function didn't call async i/o operation, simple try/catch in route handler ok (i suppose), this:
router.get('/error/:error_id', (req, res, next) => { try{ my_function(); } catch(e){ next(e); }; } function my_function(){ // stuff var f = fs.readfilesync("blablabla"); // possibly throws error } hope make sense.
you totally correct should pass next callback my_function since fs.readfile asynchronous.
router.get('/error/:error_id', (req, res, next) => { my_function(next); } function my_function(next) { fs.readfile("blablabla", function (err, data) { if (err) { next(err); } else { // process data // don't forget call `next` send respond client } }); } by way, cannot do
var f = fs.readfile(...) because fs.readfile asynchronous. data should handled within callback.
Comments
Post a Comment