如何在 TypeScript 中执行 try catch 和 finally 语句?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54649465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do try catch and finally statements in TypeScript?
提问by Raja
I have error in my project, i need handle this by using try, catchand finally. I can use this in JavaScript but in not in Typescript. When i put Exceptionas argument in typescript catchstatement, which is not accepting this? here is the code.
我的项目有错误,我需要使用try、catch和finally来处理这个问题。我可以在 JavaScript 中使用它,但不能在 Typescript 中使用。当我在 typescript catch语句中将Exception作为参数时,哪个不接受这个?这是代码。
private handling(argument: string): string {
try {
result= this.markLibrary(argument);
}
catch(e:Exception){
result = e.Message;
}
return result;
}
I need a exception message here but I can't get. And I got the below error.
我需要这里的异常消息,但我无法得到。我得到了以下错误。
Catch clause variable cannot have a type annotation.
Catch 子句变量不能有类型注释。
回答by Titian Cernicova-Dragomir
Typescript does not support annotations on the catch variable. There is a proposal to allow this but it is still being discussed (see here)
Typescript 不支持 catch 变量上的注释。有一项提议允许这样做,但仍在讨论中(请参阅此处)
Your only solution is to use a type assertion or an extra variable
您唯一的解决方案是使用类型断言或额外的变量
catch(_e){
let e:Error= _e;
result = e.message;
}
catch(e){
result = (e as Error).message;
}
Unfortunately this will work as well and is completely unchecked:
不幸的是,这也可以工作,并且完全不受检查:
catch(e){
result = e.MessageUps;
}
Note
笔记
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
正如你在提案的讨论中所读到的,在 JS 中并不是所有抛出的东西都必须是一个Error
实例,所以要注意这个假设
Maybe tslint with no-unsafe-any
would help catch this.
也许 tslint withno-unsafe-any
将有助于抓住这一点。
回答by Nguyen Phong Thien
Firstly, you need to define the result
variable
首先,您需要定义result
变量
let result;
Secondly, you can't define the type of e - as the message said, so in case you want to force the type of e, use
其次,你不能定义 e 的类型 - 正如消息所说,所以如果你想强制 e 的类型,使用
catch(e){
result = (e as Exception).Message;
}
or
或者
catch(e){
result = (<Exception>e).Message;
}
Otherwise, it should still work because e will have the type as any
否则,它应该仍然有效,因为 e 的类型为 any
catch (e) {
result = e.Message;
}