Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 127 additions & 5 deletions eslint-factory/src/rules/no-throw-plain-object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ describe("no-throw-plain-object", () => {
expect(noThrowPlainObjectRule.meta.docs.url).toBe("https://github.com/github/gh-aw/tree/main/eslint-factory#no-throw-plain-object");
});

it("hasSuggestions enabled", () => {
expect(noThrowPlainObjectRule.meta.hasSuggestions).toBe(true);
});

it("valid: throwing Error instances is allowed", () => {
ruleTester.run("no-throw-plain-object", noThrowPlainObjectRule, {
valid: [
Expand All @@ -30,25 +34,143 @@ describe("no-throw-plain-object", () => {
});
});

it("invalid: throwing a plain object literal is flagged", () => {
it("invalid: throwing a plain object literal is flagged with suggestion", () => {
ruleTester.run("no-throw-plain-object", noThrowPlainObjectRule, {
valid: [],
invalid: [
{
code: `throw { code: -32602, message: "Invalid params" };`,
errors: [{ messageId: "noThrowPlainObject" }],
errors: [
{
messageId: "noThrowPlainObject",
suggestions: [
{
messageId: "useObjectAssign",
output: `throw Object.assign(new Error("Invalid params"), { code: -32602 });`,
},
],
},
],
},
{
code: `throw { message: "not found" };`,
errors: [{ messageId: "noThrowPlainObject" }],
errors: [
{
messageId: "noThrowPlainObject",
suggestions: [
{
messageId: "useObjectAssign",
output: `throw new Error("not found");`,
},
],
},
],
},
{
code: `if (bad) { throw { code: 500, message: "internal" }; }`,
errors: [{ messageId: "noThrowPlainObject" }],
errors: [
{
messageId: "noThrowPlainObject",
suggestions: [
{
messageId: "useObjectAssign",
output: `if (bad) { throw Object.assign(new Error("internal"), { code: 500 }); }`,
},
],
},
],
},
{
code: `function f() { throw {}; }`,
errors: [{ messageId: "noThrowPlainObject" }],
errors: [
{
messageId: "noThrowPlainObject",
suggestions: [
{
messageId: "useObjectAssign",
output: `function f() { throw new Error(); }`,
},
],
},
],
},
],
});
});

it("suggestion: without-message property uses new Error() with full residual", () => {
ruleTester.run("no-throw-plain-object", noThrowPlainObjectRule, {
valid: [],
invalid: [
{
code: `throw { code: -32602 };`,
errors: [
{
messageId: "noThrowPlainObject",
suggestions: [
{
messageId: "useObjectAssign",
output: `throw Object.assign(new Error(), { code: -32602 });`,
},
],
},
],
},
],
});
});

it("suggestion: JSON-RPC shape with code, message, data", () => {
ruleTester.run("no-throw-plain-object", noThrowPlainObjectRule, {
valid: [],
invalid: [
{
code: `throw { code: -32602, message: "Invalid params", data: { field: "name" } };`,
errors: [
{
messageId: "noThrowPlainObject",
suggestions: [
{
messageId: "useObjectAssign",
output: `throw Object.assign(new Error("Invalid params"), { code: -32602, data: { field: "name" } });`,
},
],
},
],
},
],
});
});

it("skip suggestion: computed key", () => {
ruleTester.run("no-throw-plain-object", noThrowPlainObjectRule, {
valid: [],
invalid: [
{
code: `throw { [key]: "value" };`,
errors: [
{
messageId: "noThrowPlainObject",
suggestions: [],
},
],
},
],
});
});

it("skip suggestion: spread element", () => {
ruleTester.run("no-throw-plain-object", noThrowPlainObjectRule, {
valid: [],
invalid: [
{
code: `throw { ...base, code: 1 };`,
errors: [
{
messageId: "noThrowPlainObject",
suggestions: [],
},
],
},
],
});
Expand Down
69 changes: 66 additions & 3 deletions eslint-factory/src/rules/no-throw-plain-object.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,44 @@
import { AST_NODE_TYPES, ESLintUtils } from "@typescript-eslint/utils";
import { AST_NODE_TYPES, ESLintUtils, TSESLint, TSESTree } from "@typescript-eslint/utils";

const createRule = ESLintUtils.RuleCreator(name => `https://github.com/github/gh-aw/tree/main/eslint-factory#${name}`);

/** Returns true when the object has properties that cannot be safely rewritten (spreads, computed keys, methods, getters/setters). */
function hasUnsafeProperties(props: TSESTree.ObjectLiteralElement[]): boolean {
return props.some(prop => {
if (prop.type === AST_NODE_TYPES.SpreadElement) return true;
if (prop.type !== AST_NODE_TYPES.Property) return true;
if (prop.computed) return true;
if (prop.kind === "get" || prop.kind === "set") return true;
if (prop.method) return true;
return false;
});
}

/** Returns the first Property whose key is the identifier or string literal "message". */
function findMessageProp(props: TSESTree.ObjectLiteralElement[]): TSESTree.Property | null {
for (const prop of props) {
if (prop.type !== AST_NODE_TYPES.Property) continue;
if (prop.computed) continue;
const { key } = prop;
if (key.type === AST_NODE_TYPES.Identifier && key.name === "message") return prop;
if (key.type === AST_NODE_TYPES.Literal && key.value === "message") return prop;
}
return null;
}

export const noThrowPlainObjectRule = createRule({
name: "no-throw-plain-object",
meta: {
type: "problem",
hasSuggestions: true,
docs: {
description:
"Disallow throwing plain object literals (`throw { ... }`). Plain objects lack a `.stack` trace and a meaningful `.message` string, making errors hard to debug and incompatible with catch-clause error utilities (getErrorMessage, etc.). Use `new Error(...)` instead, and attach extra context via `Object.assign` or the `cause` option.",
},
schema: [],
messages: {
noThrowPlainObject: "Throwing a plain object literal loses the stack trace. Use `new Error(message)` instead; attach extra fields with `Object.assign(new Error(message), { ... })` if needed.",
useObjectAssign: "Rewrite as `Object.assign(new Error(...), { ... })`.",
},
},
defaultOptions: [],
Expand All @@ -21,9 +47,46 @@ export const noThrowPlainObjectRule = createRule({
ThrowStatement(node) {
const arg = node.argument;
if (!arg) return;
if (arg.type === AST_NODE_TYPES.ObjectExpression) {
context.report({ node: arg, messageId: "noThrowPlainObject" });
if (arg.type !== AST_NODE_TYPES.ObjectExpression) return;

const { properties: props } = arg;

if (hasUnsafeProperties(props)) {
context.report({ node: arg, messageId: "noThrowPlainObject", suggest: [] });
return;
}
Comment thread
Copilot marked this conversation as resolved.

context.report({
node: arg,
messageId: "noThrowPlainObject",
suggest: [
{
messageId: "useObjectAssign",
fix(fixer: TSESLint.RuleFixer) {
const src = context.sourceCode;

// throw {} → throw new Error()
if (props.length === 0) {
return fixer.replaceText(arg, "new Error()");
}

const msgProp = findMessageProp(props);
const errorArg = msgProp ? src.getText(msgProp.value) : "";
const residual = props.filter(p => p !== msgProp);
const newErr = errorArg ? `new Error(${errorArg})` : "new Error()";

// throw { message: x } → throw new Error(x)
if (residual.length === 0) {
return fixer.replaceText(arg, newErr);
}

// throw { code, message, data } → throw Object.assign(new Error(message), { code, data })
const residualText = residual.map(p => src.getText(p)).join(", ");
return fixer.replaceText(arg, `Object.assign(${newErr}, { ${residualText} })`);
},
},
],
});
},
};
},
Expand Down
Loading