Can I throw error in an async function?

35,223

I would do:

async function asyncFunc() {
  try {
    await somePromise();
  } catch (error) {
    throw error;
  }
}

But I think it comes to personal preference I guess? You could always return Promise.reject(new Error(error));.

Share:
35,223

Related videos on Youtube

serge1peshcoff
Author by

serge1peshcoff

I am a student and programmer. Learning Rails backend now.

Updated on July 09, 2022

Comments

  • serge1peshcoff
    serge1peshcoff almost 2 years

    I am using async/await in my Node.js project. And in some places I need to return an error from async function. If I'd use Promises, I could've accomplish it this way:

    function promiseFunc() {
      return new Promise((res, rej) => {
        return rej(new Error('some error'))
      })
    }
    

    But I'm using async function, so no res and rej methods are there. So, the question: can I throw errors in async functions? Or is it considered a good/bad practice?

    An example of what I want to do:

    async function asyncFunc() {
      throw new Error('some another error')
    }
    

    I can also rewrite it this way:

    async function anotherAsyncFunc() {
      return Promise.reject(new Error('we need more errors!'))
    }
    

    but the first one looks more clear to me, and I'm not sure which one should I use.

  • Manohar Reddy Poreddy
    Manohar Reddy Poreddy over 6 years
    As of today, there is another link that may help: makandracards.com/makandra/…
  • federicojasson
    federicojasson over 5 years
    Be aware that the provided link doesn't address await/async behavior, but asynchronous execution with promises. One of the beautiful things about await/async is that exceptions thrown from async functions are wrapped in rejected promises automatically, so it's perfectly safe to do so.
  • Alnitak
    Alnitak over 5 years
    why throw new Error(error) instead of just throw error ?
  • curv
    curv about 5 years
    some linters hate 'throw error'
  • Dr. Jan-Philip Gehrcke
    Dr. Jan-Philip Gehrcke over 4 years
    "some linters hate 'throw error'" -- why? bad linter? Probably. You can leave out the new. See stackoverflow.com/a/13294683/145400.
  • Melroy van den Berg
    Melroy van den Berg over 2 years
    @Dr.Jan-PhilipGehrcke But error is already of type Error. You really do not need to wrap it again into an error object.