I am using an async
function to call an existing promise-based API which rejects the promise with a typed error.
You could mock this behavior like this:
interface ApiError { code: number; error: string; } function api(): Promise<any> { return new Promise((resolve, reject) => { reject({ code: 123, error: "Error!" }); }); }
Now with promises, I can annotate the error type to ApiError
:
api().catch((error: ApiError) => console.log(error.code, error.message))
But when using async
if I try to annotate the error type in try ... catch()
:
async function test() { try { return await api(); } catch (error: ApiError) { console.log("error", error); } }
It compiles with error:
Catch clause variable cannot have a type annotation.
How, then, do I know what kind of error I'm expecting? Do I need to write an assertion in the catch()
block? Is that a bug/incomplete feature of async?
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. Be aware when wrapping errors and rethrowing, that you lose the stack trace with the origin of the error.
The last way to handle an error with async/await is called a higher order function. We have talked about this a couple of times now. A higher order function is a function that returns another function. The way it works is you go ahead and define all of your functions, just as if you were never to have any errors.
You should handle unexpected errors in your async functions in the calling function. The run() function shouldn't be responsible for handling every possible error, you should instead do run(). catch(handleError) .
An Asynchronous error happens independent of user program like an error in hardware, OS of CPU calls error OBs to handle it.A synchronous error happens when a problem is while processing the user program.
In TypeScript, catch
clause variables may not have a type annotation (aside from, as of TypeScript 4.0, unknown
). This is not specific to async
. Here's an explanation from Anders Hejlsberg:
We don't allow type annotations on catch clauses because there's really no way to know what type an exception will have. You can throw objects of any type and system generated exceptions (such as out of memory exception) can technically happen at any time.
You can check for the existence of error.code
and error.message
properties (optionally using a user-defined type guard) in the catch body.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With