如何在 async catch() 中使用类型错误 [英] How do you use typed errors in async catch()

查看:60
本文介绍了如何在 async catch() 中使用类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 async 函数调用现有的基于 Promise 的 API,该 API 拒绝带有类型错误的 Promise.

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!" });
  });
}

现在有了promise,我可以将错误类型注释为ApiError:

Now with promises, I can annotate the error type to ApiError:

api().catch((error: ApiError) => console.log(error.code, error.message))

但是在使用 async 时,如果我尝试在 try ... catch() 中注释错误类型:

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);
  }
}

编译出错:

Catch 子句变量不能有类型注解.

Catch clause variable cannot have a type annotation.

那么,我怎么知道我在期待什么样的错误?我需要在 catch() 块中编写断言吗?这是异步的错误/不完整功能吗?

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?

推荐答案

在 TypeScript 中,catch 子句变量可能没有类型注释(除了 从 TypeScript 4.0 开始unknown).这并不特定于 async.这是安德斯·海尔斯伯格的解释:

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:

我们不允许在 catch 子句上使用类型注释,因为真的无法知道异常将具有什么类型.您可以抛出任何类型的对象,而且系统生成的异常(例如内存不足异常)在技术上可以随时发生.

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.

您可以检查 error.codeerror.message 属性是否存在(可选地使用 用户定义的类型保护) 在捕获体中.

You can check for the existence of error.code and error.message properties (optionally using a user-defined type guard) in the catch body.

这篇关于如何在 async catch() 中使用类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆