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));
.
Related videos on Youtube
Author by
serge1peshcoff
I am a student and programmer. Learning Rails backend now.
Updated on July 09, 2022Comments
-
serge1peshcoff almost 2 years
I am using
async/await
in my Node.js project. And in some places I need to return an error fromasync
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 nores
andrej
methods are there. So, the question: can Ithrow
errors inasync
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 over 6 yearsAs of today, there is another link that may help: makandracards.com/makandra/…
-
federicojasson over 5 yearsBe aware that the provided link doesn't address
await
/async
behavior, but asynchronous execution with promises. One of the beautiful things aboutawait
/async
is that exceptions thrown fromasync
functions are wrapped in rejected promises automatically, so it's perfectly safe to do so. -
Alnitak over 5 yearswhy
throw new Error(error)
instead of justthrow error
? -
curv about 5 yearssome linters hate 'throw error'
-
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 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.