简体   繁体   中英

There is ESLint rule to avoid try-catch if there just one line?

Let's say I have this code:


export class a {

    private async func(){

        try {
            await something();
        } catch (error) {
          /////
        }

    }
}

I want to avoid the use of try-catch when there is only one line in the try block and instead use catch like this:

await something().catch(err => {…});

There is any ESLint rule that will raise an error for that?

Thanks!

EDIT 1

I tried to use the no-restricted-syntax rule with my @typescript-eslint/parser according to the AST, but it does not work:

    "no-restricted-syntax": [
      "error",
      {
        "selector": "TryStatement > BlockStatement[body.length=0]",
        "message": "No try block for one line!"
      }
    ],

You can use the following selector:

 "selector": "TryStatement > BlockStatement[body.length=1] AwaitExpression"

This will catch any try statement which has a block with only one child node that includes an await expression.

If you want to be less specific you can just remove the "AwaitExpression" to catch any try statement with only a single line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM