如何在 TypeScript 中执行 try catch 和 finally 语句?

Raj*_*aja 34 error-handling try-catch typescript

我的项目中有错误,我需要使用trycatchfinally来处理这个问题。

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

当我在 typescript catch语句中将Exception作为参数时,为什么它不接受这个?

这是代码。

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

我需要这里的异常消息,但我无法得到。我得到了以下错误。

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

Tit*_*mir 31

Typescript 不支持 catch 变量上的注释。有一项提议允许这样做,但仍在讨论中(请参阅此处

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

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

catch(e){
    result = (e as Error).message;
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这也可以工作并且完全不受检查:

catch(e){
    result = e.MessageUps;
}
Run Code Online (Sandbox Code Playgroud)

笔记

正如你在提案的讨论中所读到的,在 JS 中并不是所有抛出的东西都必须是一个Error实例,所以要注意这个假设

也许 tslint withno-unsafe-any将有助于抓住这一点。


for*_*d04 22

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. (docs)

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 
}
Run Code Online (Sandbox Code Playgroud)

Playground

Update: TypeScript 4.4 provides a config flag --useUnknownInCatchVariables to let catch variables default to type unknown. This is also automatically enabled with the --strict flag.


MdJ*_*009 20

可以试试这个

try {...}
catch (e) {
    console.log((e as Error).message);
}
Run Code Online (Sandbox Code Playgroud)

打字也any可以。

try {...}
    catch (e:any) {
        console.log(e.message);
    }
Run Code Online (Sandbox Code Playgroud)

instanceof抛出错误。

try {...}
    catch (e) {
        console.log((e instanceof Error).message);
    }
Run Code Online (Sandbox Code Playgroud)


Ngu*_*ien 13

首先,您需要定义result变量

let result;
Run Code Online (Sandbox Code Playgroud)

其次,您无法定义 e 的类型 - 正如消息所述,因此如果您想强制 e 的类型,请使用

catch(e){
    result = (e as Exception).Message;
}
Run Code Online (Sandbox Code Playgroud)

或者

catch(e){
    result = (<Exception>e).Message;
}
Run Code Online (Sandbox Code Playgroud)

否则,它应该仍然有效,因为 e 的类型为any

catch (e) {
    result = e.Message;
}
Run Code Online (Sandbox Code Playgroud)