eslint: Ignore `catch` block in the `no-empty` rule

Problem

The following is very common pattern when you don’t care about an exception:

try {
  foo();
} catch (err) {}

But it’s caught by the no-empty rule.

I want the rule to catch empty blocks, but ignore the catch block as it’s empty because it’s required by JS, not because I want it there.

I know I can put in a // empty comment there, but that feels like an unuseful reiteration of the obvious.

Possible solution 1

Ignore catch by default as it’s required to be empty and not really useful to require it not to be empty. This is the preferred solution.

Possible solution 2

Add an option that defines exceptions in the form of keywords:

{
  "no-empty": [2, {"exceptions": "catch"}]
}

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 15 (11 by maintainers)

Most upvoted comments

@sindresorhus We provide a way to customize this behavior, if I’m not mistaken this code will lint just fine

try {
    foo();
} catch(err) {
    // I want application to not crush, but don't care about the message
}

Any comment inside a block will mark it as non-empty. Leaving comments in the cases where you used try catch but ignoring cache is a good idea, if somebody else is going to be looking at your code. But in general, I do see your point.

@sindresorhus

The following is very common pattern when you don’t care about an exception:

try {
  foo();
} catch (err) {}

This is a HORRIBLE, HORRIBLE pattern that, unfortunately, is very common in javascript. But it shouldn’t be perpetuated explicitly or implicitly. At the very least you should provide a comment explaining why you are ignoring that exception. Better yet, you should do an instanceof check to only ignore Errors of a certain type, and rethrow all others, which would also satisfy this rule.

p.s. Excuse me for the strong formatting, but good error handling is something I feel VERY STRONGLY about. 😄

jslint has an IMO nice approach where if you name the variable ignore, well, then, it’s ignored. And it complains if the variable named ignore is used in a catch block. I’d assume it comes with the option to disable/enable I guess. Would that work for eslint?