Repository navigation
[eslint-miner] feat(eslint): add require-fetch-try-catch rule - #47763
Conversation
Adds a new ESLint rule that requires `await fetch(...)` calls in actions/setup/js to be wrapped in try/catch. The Fetch API throws TypeError on network failures (DNS errors, connection refused, request aborted, etc.). Without a try/catch, these failures produce an unhandled exception that crashes the action with no useful diagnostic. Evidence in actions/setup/js: - artifact_client.cjs lines 217, 269, 319, 335 — four fetch calls outside try/catch that the new rule flags as warnings. Rule details: - Flags any `await fetch(...)` expression not inside a try block - Provides a fix suggestion for ExpressionStatement context - Ignores non-fetch awaits (axios, octokit, etc.) - Registered as 'warn' in eslint.config.cjs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
|
🧠 Matt Pocock Skills Reviewer has completed the skills-based review. ✅ |
|
✅ Design Decision Gate 🏗️ completed the design decision gate check. No ADR enforcement needed: PR #47763 does not have the 'implementation' label and has 0 new lines of code in business logic directories (threshold: 100). |
|
✅ PR Code Quality Reviewer completed the code quality review. |
|
✅ Test Quality Sentinel completed test quality analysis. |
There was a problem hiding this comment.
Pull request overview
Adds an ESLint rule requiring direct await fetch(...) calls to be protected by try/catch.
Changes:
- Implements and registers
require-fetch-try-catch. - Adds CommonJS and ES module tests.
- Enables the rule for setup JavaScript linting.
Show a summary per file
| File | Description |
|---|---|
eslint-factory/src/rules/require-fetch-try-catch.ts |
Implements detection and suggestions. |
eslint-factory/src/rules/require-fetch-try-catch.test.ts |
Tests valid and invalid cases. |
eslint-factory/src/index.ts |
Registers the rule. |
eslint-factory/eslint.config.cjs |
Enables the rule as a warning. |
Review details
Tip
Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
- Files reviewed: 4/4 changed files
- Comments generated: 2
- Review effort level: Medium
|
|
||
| return { | ||
| AwaitExpression(node) { | ||
| if (!isAwaitFetchCall(node)) return; |
| return { | ||
| AwaitExpression(node) { | ||
| if (!isAwaitFetchCall(node)) return; | ||
| if (isInsideTryBlock(sourceCode, node)) return; |
There was a problem hiding this comment.
The require-fetch-try-catch rule is well-structured and follows existing patterns in the codebase. The implementation correctly identifies await fetch(...) outside try blocks, provides fix suggestions for ExpressionStatement contexts only (appropriately skipping VariableDeclaration where the binding would escape the try scope), and reuses shared utilities (isInsideTryBlock, buildTryCatchSuggestion). Tests cover valid/invalid cases, both CJS and ESM, nested try blocks, and loops. No issues found.
🧵 Reviewed using Impeccable skills by Impeccable Skills Reviewer · sonnet46 · 15.9 AIC · ⌖ 4.48 AIC · ⊞ 5K
🧪 Test Quality Sentinel Report
📊 Metrics (7 tests)
|
There was a problem hiding this comment.
✅ Test Quality Sentinel: 76/100 Acceptable. 85.7% design tests (6 of 7), 14.3% implementation tests (1 of 7, threshold: 30%). Strong behavioral contract coverage with good edge cases. Minor issue: Test 5 duplicates Test 4 with minimal ESM-specific coverage; Test 7 lacks suggestion verification unlike Test 4. See detailed analysis in comment above.
There was a problem hiding this comment.
Skills-Based Review 🧠
Applied /tdd and /codebase-design — commenting with minor improvement opportunities, no blocking issues.
📋 Key Themes & Highlights
Positive Highlights
- ✅ Strong test coverage: 7 test cases across CJS/ESM, nested try, loop, and VariableDeclaration contexts
- ✅ Clean reuse of shared
try-catch-rule-utilshelpers — consistent with existing rules - ✅ Fix suggestion produces idiomatic
new Error(..., { cause: err })— good error hygiene - ✅ PR description includes real evidence (4 violations in
artifact_client.cjs) — very helpful context
Issues Found (non-blocking)
- False positive with imported
fetch—callee.name === "fetch"matches any identifier namedfetch, includingimport fetch from "node-fetch". Worth documenting or adding a test for this boundary. - Missing member-fetch boundary test —
await client.fetch(url)is correctly ignored, but no test asserts this. Easy to add. - Empty
urlTextfallback —fetch()with no arguments results in an empty string in the diagnostic message; a clearer placeholder like/* no url */would improve the developer experience.
🧠 Reviewed using Matt Pocock's skills by Matt Pocock Skills Reviewer · sonnet46 · 36.9 AIC · ⌖ 4.86 AIC · ⊞ 6.7K
Comment /matt to run again
| if (node.type !== AST_NODE_TYPES.AwaitExpression) return false; | ||
| const argument = node.argument; | ||
| if (argument.type !== AST_NODE_TYPES.CallExpression) return false; | ||
| const callee = argument.callee; |
There was a problem hiding this comment.
[/tdd] The identifier-only check callee.name === "fetch" will produce false positives when fetch is an imported alias (e.g., import fetch from 'node-fetch' or const fetch = require('cross-fetch')). A custom wrapper may already handle errors.
💡 Suggested test + fix direction
Add a valid test case documenting the current behaviour:
// imported fetch — currently flagged even if it wraps error handling
import fetch from 'node-fetch';
async function f() { const res = await fetch(url); }If scope analysis is out of scope, document the known false-positive in the rule description so consumers can suppress it per file.
@copilot please address this.
| if (!isAwaitFetchCall(node)) return; | ||
| if (isInsideTryBlock(sourceCode, node)) return; | ||
|
|
||
| const fetchCall = node.argument as TSESTree.CallExpression; |
There was a problem hiding this comment.
[/tdd] No test covers fetch called as a method/member (obj.fetch(url)) — the rule correctly ignores this since it checks only for a bare fetch identifier, but a test makes the boundary explicit and prevents future regressions if the detection logic is ever expanded.
💡 Suggested valid test case
it("valid: member fetch is not flagged", () => {
cjsRuleTester.run("require-fetch-try-catch", requireFetchTryCatchRule, {
valid: [
`async function f() { const res = await client.fetch(url); }`,
],
invalid: [],
});
});@copilot please address this.
| const stmt = findEnclosingStatement(sourceCode, node); | ||
|
|
||
| context.report({ | ||
| node, |
There was a problem hiding this comment.
[/codebase-design] urlText falls back to "" when fetchCall.arguments[0] is undefined, which silently produces the message Wrap \await fetch()` in try/catch. fetch()with no arguments is already aTypeError` at call time, but the empty string makes the diagnostic misleading for other zero-arg cases.
💡 Suggested improvement
const urlText = firstArg !== undefined ? sourceCode.getText(firstArg as TSESTree.Node) : "/* no url */";Or short-circuit with return when there are no arguments, since fetch() with no args is invalid JS anyway and the rule cannot usefully wrap it.
@copilot please address this.
There was a problem hiding this comment.
One non-blocking issue; logic is sound
The rule implementation is correct: properly handles deferred async boundaries, intentionally omits suggestions for (where wrapping would break subsequent uses of the declared variable — documented in the tests), and the overall pattern follows established conventions in the plugin.
One medium issue with the message formatting — see inline comment.
Other items considered and dropped
- ** deprecation**: pattern is used identically across all existing rules in the codebase; not a regression introduced here.
- VariableDeclaration gets no suggestion: explicitly intentional and documented in the test comments — wrapping only the declaration leaves subsequent uses of the variable outside the try block.
- Aliased fetch / globalThis.fetch: caller-controlled indirection is out of scope for identifier-based rules; consistent with how all other rules in the plugin work.
- fire-and-forget fetch: explicitly out of scope per the rule name and docs.
🔎 Code quality review by PR Code Quality Reviewer · sonnet46 · 47.3 AIC · ⌖ 4.64 AIC · ⊞ 5.7K
Comment /review to run again
|
|
||
| const fetchCall = node.argument as TSESTree.CallExpression; | ||
| const firstArg = fetchCall.arguments[0]; | ||
| const urlText = firstArg !== undefined ? sourceCode.getText(firstArg as TSESTree.Node) : ""; |
There was a problem hiding this comment.
Untruncated URL text injected verbatim into the lint message — a complex first argument (template literal, function call, chained expression) produces multi-line or extremely long diagnostic output that breaks IDE lint overlays and CI log readability.
💡 Suggested fix
Truncate urlText before embedding it in the message:
const MAX_URL_LEN = 60;
const rawUrlText =
firstArg !== undefined ? sourceCode.getText(firstArg as TSESTree.Node) : "";
const urlText =
rawUrlText.length > MAX_URL_LEN ? rawUrlText.slice(0, MAX_URL_LEN) + "..." : rawUrlText;This prevents template literals like `${baseUrl}/api/endpoint` or function calls like buildUrl(config.host, path, query) from producing garbled or truncated IDE tooltip text.
|
@copilot run pr-finisher skill |
- Add hasLocalBinding() check to skip locally-shadowed fetch identifiers
(e.g. async function f(fetch) { await fetch(url); }) — mirrors the same
guard in require-new-url-try-catch.ts
- Replace shared isInsideTryBlock with a local version that stops at any
function boundary (FunctionDeclaration, FunctionExpression,
ArrowFunctionExpression); the shared helper only crossed deferred
callbacks so named/stored async functions inside an outer try block were
incorrectly treated as protected
- Add tests: valid local-binding cases and invalid nested-function cases
Co-authored-by: pelikhan <4175913+pelikhan@users.noreply.github.com>
Both review threads addressed in commit Thread 1 (line 43 — local binding): Added Thread 2 (line 44 — function boundary): Replaced the shared Three new test cases cover the boundary scenarios; two existing test groups cover the local-binding case. All 9 tests pass. |
|
🎉 This pull request is included in a new release. Release: |
test