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

Time:07-10

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!"
      }
    ],

CodePudding user response:

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.

  • Related