Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to wrap an await/async try/catch block to every function?

So i'm using express.js and looking into using async/await with node 7. Is there a way that I can still catch errors but get rid of the try/catch block? Perhaps a function wrapper? I'm not sure how this would actually execute the function's 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 this...?

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 similar to this:

var wrapper = function(f) {
    return function() {
        try {
            f.apply(this, arguments);
        } catch(e) {
            customErrorHandler(e)
        }
    }
}

This would somehow handle the try/catch block but doesn't 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 to every function in Javascript? for the non-async example.

like image 648
Neverlax Avatar asked Dec 27 '16 17:12

Neverlax


People also ask

Can you have multiple awaits in one async function?

In order to run multiple async/await calls in parallel, all we need to do is add the calls to an array, and then pass that array as an argument to Promise. all() . Promise. all() will wait for all the provided async calls to be resolved before it carries on(see Conclusion for caveat).

How do you handle catch in async-await?

We can handle this in two ways: We call thisThrows() in an async function and await the thisThrows() function. We chain the thisThrows() function call with a . catch() call.

Does Try Catch work with async?

Since you're working with what looks like synchronous code, async functions can use try... catch to handle any errors. try... catch is the most common way to handle exceptions when using async/await.

Is async-await better than then catch?

In my view, unless a library or legacy codebase forces you to use then/catch , the better choice for readability and maintainability is async/await .


2 Answers

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);
    };
}
like image 163
Bergi Avatar answered Oct 07 '22 15:10

Bergi


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);
});
like image 20
Cooper Hsiung Avatar answered Oct 07 '22 13:10

Cooper Hsiung