node.js - Acitvate express/node error handler on user code exception -
i have code follows:
app.js
app.use(app.router) app.use(function(err, req, res, next) { res.render(errorpage) }) app.get('/', function(req,res,next) { module1.throwexception(function{ ... }); });
module1.js
exports.thowexception = function(callback) { // throws typeerror exception. // follwoing 2 lines getting executed async // simplicity removed async code var myvar = undefined; myvar['a'] = 'b' callback() }
with exception in module1.js, node prcoess dies. instead wanted render error page.
i tried try ... catch in app.get(..), did not help.
how can this??
you can't use try ... catch
asynchronous code. in post can find basic principles error handling in node.js. in situation should return error first parameter of callback module instead of throwing , next call error handler. because error handling function after app.route handler, should check not found error if of route doesn't match. next code simplified example.
app.js
app.use(app.router) app.use(function(err, req, res, next) { if (err) { res.render(errorpage); // handle internal error } else { res.render(error404page); // handle not found error } }) app.get('/', function(req, res, next) { module1.notthrowexception(function(err, result) { if (err) { next(new error('some internal error')); } // send response user here }); });
module1.js
exports.notthrowexception = function(callback) { var myvar = undefined; try { myvar['a'] = 'b'; } catch(err) { callback(err) } // other calculations here callback(null, result); // report result success }
Comments
Post a Comment