Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I throw error in an async function? [duplicate]

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.

like image 430
serge1peshcoff Avatar asked Jun 15 '17 08:06

serge1peshcoff


People also ask

How do you handle error in async?

catch (in combination with async functions) and the . catch() approaches to handle errors for asynchronous code. When returning a promise within a try block, make sure to await it if you want the try... catch block to catch the error.

Does await throw error?

If a promise resolves normally, then await promise returns the result. But in the case of a rejection, it throws the error, just as if there were a throw statement at that line. In real situations, the promise may take some time before it rejects. In that case there will be a delay before await throws an error.


1 Answers

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

like image 130
Paulooze Avatar answered Oct 09 '22 02:10

Paulooze