42

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.

0

1 Answer 1

41

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));.

Sign up to request clarification or add additional context in comments.

6 Comments

As of today, there is another link that may help: makandracards.com/makandra/…
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.
why throw new Error(error) instead of just throw error ?
some linters hate 'throw error'
"some linters hate 'throw error'" -- why? bad linter? Probably. You can leave out the new. See stackoverflow.com/a/13294683/145400.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.