Issue
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?
Solution
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.
Answered By - Steven Barnett
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.