Try/Catch always needed for await?
a.d.bergi at web.de
Fri Oct 14 13:30:36 UTC 2016
Jordan Rome schrieb:
> My apologies if this has already been discussed but what is the "preferred"
> pattern for using await ? Since await, which runs on promises, will now
> throw if the promise is rejected (preventing execution of code after the
> await and killing the process in Node), is it neccesary to always be
> wrapping await in try/catch?
No. Just like in synchronous code, you only wrap a part of your code in
try-catch if you actually want to *handle* an exception.
If you don't handle it, it will bubble as usual and reject the promise
returned by the `async function`. Let the caller deal with the
exceptions you can't handle - just like always.
Of course, in the top-level invocation it might be a good idea to use a
`catch` (or the `.catch()` method) to catch any exceptions and log them
to whereever you want if you don't want to get an unhandled rejection,
but those are usually exceptions you *don't expect* so you might not
need to deal with them at all.
More information about the es-discuss