如何在 TypeScript 中尝试 catch 和 finally 语句?

我在我的项目中有错误,我需要使用 试试看catch终于来处理这个问题。

我可以在 JavaScript 中使用它,但不能在 Typecript 中使用。

当我把 例外 作为参数在类型脚本 接住语句,为什么它不接受这一点?

这是密码。

private handling(argument: string): string {
try {
result= this.markLibrary(argument);
}
catch(e:Exception){
result = e.Message;
}
return result;
}

我需要一个异常消息在这里,但我不能得到。我得到了下面的错误。

Catch 子句变量不能有类型注释。

198024 次浏览

Firstly, you need to define the result variable

let result;

其次,您不能像消息所说的那样定义 e-的类型,所以如果您想强制使用 e 的类型,请使用

catch(e){
result = (e as Exception).Message;
}

或者

catch(e){
result = (<Exception>e).Message;
}

否则,它应该仍然可以工作,因为 e 的类型是 any

catch (e) {
result = e.Message;
}

剪辑

类型脚本4.0增加了在 catch 变量(问题)上指定 unknownany的能力,类型脚本4.4增加了在使用 useUnknownInCatchVariables 标志的 catch 变量(公关)上使 unknown成为默认值的能力。

有了这面旗帜,现在可以做到以下几点:

catch(e){
result = e.message; // error under useUnknownInCatchVariables
if (typeof e === "string") {
e.toUpperCase() // works, `e` narrowed to string
} else if (e instanceof Error) {
e.message // works, `e` narrowed to Error
}
}

仍然不支持在 catch 变量上指定任意类型。

原始答案

类型脚本不支持 catch 变量上的注释。有一个建议允许这样做,但仍在讨论中(见 here)

您唯一的解决方案是使用类型断言或额外的变量

catch(_e){
let e:Error= _e;
result = e.message;
}


catch(e){
result = (e as Error).message;
}

不幸的是,这种方法同样有效,而且完全不受控制:

catch(e){
result = e.MessageUps;
}

注意

As you can read in the discussion on the proposal, in JS not everything that is thrown has to be an Error instance, so beware of this assumption

也许用 no-unsafe-any可以帮助捕捉到这个。

With TypeScript 4.0, you can set unknown as catch clause variable type:

unknown is safer than any because it reminds us that we need to perform some sorts of type-checks before operating on our values. (医生)

try {  /* ... */ }
catch (e: unknown) { // <-- note `e` has explicit `unknown` type
e.message // errors
if (typeof e === "string") {
e.toUpperCase() // works, `e` narrowed to string
} else if (e instanceof Error) {
e.message // works, `e` narrowed to Error
}
// ... handle other error types
}

Playground

更新: TypeScript 4.4提供了一个配置标志 --useUnknownInCatchVariables,让 catch 变量默认为 unknown类型。这也是通过 --strict标志自动启用的。

对我有效的就是这样。 打印到终端:

    catch(error){
log('any_text', error as Error);
}

或者调用 metod:

    catch(error){
anything_here((error as Error).message),
}

答案很简单

catch (e) {
const error = e as <Your custom error type>;
...
}

可以试试这个

try {...}
catch (e) {
console.log((e as Error).message);
}

any类型也可以工作。

try {...}
catch (e:any) {
console.log(e.message);
}

But instanceof throw error.

try {...}
catch (e) {
console.log((e instanceof Error).message);
}