35

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.

serge1peshcoff
  • 4,342
  • 11
  • 45
  • 76

1 Answers1

36

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

Melroy van den Berg
  • 2,697
  • 28
  • 31
Paulooze
  • 1,147
  • 10
  • 13
  • 2
    As of today, there is another link that may help: https://makandracards.com/makandra/43653-javascript-don-t-throw-exceptions-from-async-functions – Manohar Reddy Poreddy Feb 14 '18 at 03:45
  • 7
    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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#Return_value), so it's perfectly safe to do so. – federicojasson Oct 29 '18 at 20:52
  • 7
    why `throw new Error(error)` instead of just `throw error` ? – Alnitak Feb 01 '19 at 10:40
  • 1
    some linters hate 'throw error' – curv Mar 20 '19 at 14:07
  • 3
    "some linters hate 'throw error'" -- why? bad linter? Probably. You can leave out the `new`. See https://stackoverflow.com/a/13294683/145400. – Dr. Jan-Philip Gehrcke Nov 28 '19 at 13:04
  • @Dr.Jan-PhilipGehrcke But `error` is already of type Error. You really do not need to wrap it again into an error object. – Melroy van den Berg Jan 08 '22 at 17:35