Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

error handling - How to do try catch and finally statements in TypeScript?

I have error in my project, and I need to handle this by using try, catch and finally.

I can use this in JavaScript but not in Typescript.

When I put Exception as argument in typescript catch statement, why it is not accepting this?

here is the code.

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

I need an exception message here but I can't get. And I got the below error.

Catch clause variable cannot have a type annotation.

question from:https://stackoverflow.com/questions/54649465/how-to-do-try-catch-and-finally-statements-in-typescript

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

1 Answer

0 votes
by (71.8m points)

Typescript does not support annotations on the catch variable. There is a proposal to allow this but it is still being discussed (see here)

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

Maybe tslint with no-unsafe-any would help catch this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...