Is there a way to wrap an await/async try/catch block to every function?
A similar answer here hope can 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);
});
So, async functions are actually promises, I came up with this solution:
const asyncWrapper = async promise => {
try {
return [null, await promise];
} catch (err) {
return [err];
}
};
const yourAsyncMethod = params => new Promise((resolve, reject) => {
resolve(params);
});
(async () => {
// Wrap the executed async method but use the await outside
const [error, result] = await asyncWrapper(yourAsyncMethod(1));
if (error) {
// Handle error
}
console.log(result);
})();
Yes, you can easily write such a wrapper for asynchronous functions as well - 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, like in this example that is more tailored to express (especially with the number of parameters):
function promiseWrapper(fn) {
return (req, res, next) => {
fn(req, res).catch(next);
};
}
If someone prefers async/await and Express-specific approach, following snippet could be useful
export function asyncWrap(fn) {
return async function wrappedFn(req, res, next) {
try {
await fn(req, res);
} catch (err) {
next(err);
}
};
}
it can be used in the router in the following way
customRouter.get('/', asyncWrap(customController.getCustomListHandler));