Is there a way to wrap a / async try / catch block for each function?

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.

+7
javascript async-await express ecmascript-2017
source share
2 answers

Yes, you can easily write such a wrapper for asynchronous functions - just use async / await :

 function wrapper(f) { return async function() { // ^^^^^ try { return await f.apply(this, arguments); // ^^^^^ } catch(e) { customErrorHandler(e) } } } 

Or you use promises directly, as in this example, which is more for expression (especially with the number of parameters):

 function promiseWrapper(fn) { return (req, res, next) => { fn(req, res).catch(next); }; } 
+5
source share

A similar answer here may help you.

 const sthError = () => Promise.reject('sth error'); const test = opts => { return (async () => { // do sth await sthError(); return 'ok'; })().catch(err => { console.error(err); // error will be catched there }); }; test().then(ret => { console.log(ret); }); 
0
source share

All Articles