Writing a Custom ESLint Rule With an AI Pair Programmer

Close-up macro photo of a green circuit board with visible traces

A custom ESLint rule is a plugin object with two parts: a meta block describing the rule, and a create(context) function that returns an AST visitor object. Pairing with an AI assistant speeds up the first draft, but the draft needs the same scrutiny you’d give a human’s first pass — this walkthrough builds one rule end to end, including the point where the AI’s first version gets an edge case wrong and RuleTester catches it, and the follow-up design decision that failure forces you to make explicitly.

Close-up macro photo of a green circuit board with visible traces
Image: bengt-re from Sweden, CC BY 2.0, via Wikimedia Commons

Why write a custom rule instead of using a generic one

ESLint ships hundreds of rules for common problems across style, correctness, and common bug patterns, but a project-specific pattern — a silently swallowed error, a banned internal API, a required logging call — usually has no generic equivalent. The rule built here, no-silent-catch, flags a catch block that’s empty or contains only a comment, which is a different (and in our experience more common) bug than what ESLint’s built-in no-empty rule targets by default — that built-in rule flags any empty block, not specifically a catch block hiding a swallowed error, so teams that want to single out error-handling code end up writing something custom either way.

Step 1: Describe the rule, get a first draft

A reasonable first prompt to an AI pair programmer: “Write an ESLint rule for the flat config format that reports an error when a catch block’s body is empty. Use the CatchClause node type.” A typical first draft looks like this:

module.exports = {
  meta: {
    type: "suggestion",
    docs: { description: "disallow empty catch blocks" },
    schema: []
  },
  create(context) {
    return {
      CatchClause(node) {
        if (node.body.body.length === 0) {
          context.report({ node, message: "Catch block is empty." });
        }
      }
    };
  }
};

This looks reasonable, and it’s wrong in a way that won’t show up until you test it — the next step is non-optional, not a formality.

Step 2: Let RuleTester find what the draft got wrong

Testing isn’t a separate chore bolted onto rule-writing; ESLint’s own RuleTester is how you find out whether a rule does what you asked it to, as opposed to what you think you asked it to:

const { RuleTester } = require("eslint");
const rule = require("./no-silent-catch");

const ruleTester = new RuleTester();
ruleTester.run("no-silent-catch", rule, {
  valid: [
    "try { risky(); } catch (e) { log(e); }"
  ],
  invalid: [
    {
      code: "try { risky(); } catch (e) {}",
      errors: [{ message: "Catch block is empty." }]
    },
    {
      // the case the first draft misses
      code: "try { risky(); } catch (e) { /* ignore: intentional */ }",
      errors: [{ message: "Catch block is empty." }]
    }
  ]
});

The second invalid case fails against the first draft. node.body.body is the catch block’s array of statements, and a comment isn’t a statement — it doesn’t appear in that array at all, regardless of whether it’s there to explain why the block is intentionally empty. The rule reports nothing, the test expects an error, and RuleTester fails exactly where it should. This is the point where pairing with an AI on rule-writing earns its keep: the draft reads correctly, compiles, and passes an eyeball check, and only a concrete failing test surfaces the gap.

Step 3: Fix it with the SourceCode API

ESLint’s SourceCode object, available as context.sourceCode in current versions, has a getCommentsInside(node) method that returns the comment tokens inside a given node — one way to check whether an apparently empty block actually contains a comment:

module.exports = {
  meta: {
    type: "suggestion",
    docs: { description: "disallow silently empty catch blocks" },
    schema: []
  },
  create(context) {
    const sourceCode = context.sourceCode;
    return {
      CatchClause(node) {
        const hasStatements = node.body.body.length > 0;
        const hasComments = sourceCode.getCommentsInside(node.body).length > 0;
        if (!hasStatements && !hasComments) {
          context.report({ node, message: "Catch block is empty." });
        }
      }
    };
  }
};

Whether a comment-only catch block should pass or fail is a judgment call, not a correctness question — this version treats an explanatory comment as evidence the omission was intentional, which is a defensible default, but the opposite choice (comments don’t count, you must log or rethrow) is equally valid depending on how strict your team wants to be. Re-running the same two RuleTester cases from Step 2, but flipping the second one’s expectation to valid if you choose that stance, is how you lock in whichever decision the team actually made, rather than leaving it as an implicit assumption buried in the AST check.

Step 4: Register the rule in a flat config

ESLint’s current flat config format registers a local rule through a plugin object, without needing to publish it as a package:

// eslint.config.js
import { defineConfig } from "eslint/config";
import noSilentCatch from "./rules/no-silent-catch.js";

export default defineConfig([
  {
    plugins: { local: { rules: { "no-silent-catch": noSilentCatch } } },
    rules: { "local/no-silent-catch": "error" }
  }
]);

The rule only runs if its severity is set to "warn" or "error" in the rules block — registering it under plugins alone has no effect on its own, which is an easy step to miss when copying a config snippet from a tutorial without reading it line by line.

Switching from a raw message to a messageId

The examples above use a literal message string for simplicity, but ESLint’s own custom-rules documentation favors declaring a messages map in meta and reporting with messageId instead:

module.exports = {
  meta: {
    type: "suggestion",
    docs: { description: "disallow silently empty catch blocks" },
    schema: [],
    messages: {
      emptyCatch: "Catch block is empty. Log, rethrow, or add a comment explaining why it's intentional."
    }
  },
  create(context) {
    const sourceCode = context.sourceCode;
    return {
      CatchClause(node) {
        const hasStatements = node.body.body.length > 0;
        const hasComments = sourceCode.getCommentsInside(node.body).length > 0;
        if (!hasStatements && !hasComments) {
          context.report({ node, messageId: "emptyCatch" });
        }
      }
    };
  }
};

Two practical benefits follow from this change: the wording can be edited in one place without touching the AST logic, and RuleTester can assert on messageId instead of the exact message string, so a later copy edit to the message text doesn’t break every existing test that checks for it word-for-word.

Rolling a new rule out without breaking CI on day one

A brand-new rule run in error mode against an existing codebase for the first time will often surface dozens of pre-existing violations at once, which is exactly the kind of surprise failure our checklist for reviewing an AI-generated GitHub Actions workflow warns against shipping straight to the main branch. Running the new rule in warn mode for an initial period, or scoping it to specific directories with ESLint’s overrides, gives a team time to clean up existing violations on its own schedule instead of discovering them as a blocked pull request the next time someone touches an old file, and it gives the rule itself a chance to prove out against real code before anyone treats its output as settled.

Common mistakes when pairing with AI on rule-writing

  • Treating a plausible-looking draft as a correct one. The first draft above compiled, ran, and looked right; only a test case built around a real edge case (a comment-only block) exposed the gap, the same pattern covered in our piece on why AI coding assistants keep suggesting deprecated APIs — confident and wrong look identical until checked.
  • Writing valid-only test cases. A rule tested only against code it shouldn’t flag will never reveal a false negative; the invalid array needs to include the tricky cases on purpose, not just the obvious one.
  • Forgetting fixable in meta when adding an auto-fix function. ESLint throws if a rule provides a fix function without declaring fixable: "code" (or "whitespace") in its meta block.
  • Not deciding the comment-only case explicitly. As above, “empty with a comment” is a real design decision a team has to make once, not an edge case to leave to whichever way the first draft happened to handle it.

One detail worth clarifying: Should a custom rule like this go through the same review process as the AI-generated code it’s meant to check? Yes, and for the same reasons — a lint rule is still code, and our four-pass AI code review approach (security, correctness, edge cases, test gaps) applies just as well to a rule file as to application code. A rule with a bug doesn’t just miss a few cases quietly; it can produce confident false positives across an entire codebase at once.

A natural follow-up: Is RuleTester the only way to validate a new rule before rolling it out? It’s the right tool for unit-level correctness, but running the finished rule against your actual codebase once, in warn mode, before flipping it to error, catches a different class of problem: patterns your test cases didn’t anticipate because you didn’t know they existed in the code yet, like a framework-specific catch block shape RuleTester’s hand-written examples never covered. The same “test against realistic edge cases before trusting the output” instinct behind our two-step prompt for useful unit tests applies here too.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top