Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

typescript - How do you use typed errors in async catch()

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...