So, I use express.js and look at using async / await using node 7. Is there a way in which I can still catch errors but get rid of the try / catch block? Perhaps a shell function? I'm not sure how this will actually execute the function code, and also call next(err) .
exports.index = async function(req, res, next) { try { let user = await User.findOne().exec(); res.status(200).json(user); } catch(err) { next(err); } }
Something like that...?
function example() { // Implements try/catch block and then handles error. } exports.index = async example(req, res, next) { let user = await User.findOne().exec(); res.status(200).json(user); }
EDIT:
Something more like this:
var wrapper = function(f) { return function() { try { f.apply(this, arguments); } catch(e) { customErrorHandler(e) } } }
This somehow handles the try / catch block, but does not work:
exports.index = wrapper(async example(req, res, next) { let user = await User.findOne().exec(); res.status(200).json(user); });
See Is there a way to add try-catch for each function in Javascript? for a non-asynchronous example.
javascript async-await express ecmascript-2017
Neverlax
source share