Skip to content
Merged
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
71 changes: 63 additions & 8 deletions src/rules/no-throw-default-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ export const meta = {
};

export function create(context: Rule.RuleContext): Rule.NodeListener {
const fileName = context.filename;
const isCliFile = fileName.includes('packages/aws-cdk/');

return {
ThrowStatement(node: ThrowStatement) {
if (node.argument.type !== 'NewExpression') {
Expand All @@ -18,20 +21,66 @@ export function create(context: Rule.RuleContext): Rule.NodeListener {
newExpr.callee.type === 'Identifier' &&
newExpr.callee.name === 'Error'
) {
context.report({
node: newExpr,
message: 'Expected a non-default error object to be thrown.',
suggest: [
const suggestions = [
{
desc: 'Replace with `ValidationError`',
fix: (fixer: Rule.RuleFixer) => {
// no existing args
if (newExpr.arguments.length === 0) {
return fixer.replaceText(newExpr, "new ValidationError('<insert error message>', this)");
}

const fixes = [
fixer.replaceText(newExpr.callee, 'ValidationError'),
];

const last = newExpr.arguments.at(-1)?.range;
if (last) {
fixes.push(
fixer.insertTextAfterRange(last, ', this'),
);
}

return fixes;
},
},
];

// Adds ToolkitError and AuthenticationError suggestions for CLI files.
if (isCliFile) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

😍

suggestions.push(
{
desc: 'Replace with `ToolkitError`',
fix: (fixer: Rule.RuleFixer) => {
// no existing args
if (newExpr.arguments.length === 0) {
return fixer.replaceText(newExpr, "new ToolkitError('<insert error message>')");
}

const fixes = [
fixer.replaceText(newExpr.callee, 'ToolkitError'),
];

const last = newExpr.arguments.at(-1)?.range;
if (last) {
fixes.push(
fixer.insertTextAfterRange(last, ', this'),
);
}

return fixes;
},
},
{
desc: 'Replace with `ValidationError`',
desc: 'Replace with `AuthenticationError`',
fix: (fixer: Rule.RuleFixer) => {
// no existing args
if (newExpr.arguments.length === 0) {
return fixer.replaceText(newExpr, "new ValidationError('<insert error message>', this)");
return fixer.replaceText(newExpr, "new AuthenticationError('<insert error message>')");
}

const fixes = [
fixer.replaceText(newExpr.callee, 'ValidationError'),
fixer.replaceText(newExpr.callee, 'AuthenticationError'),
];

const last = newExpr.arguments.at(-1)?.range;
Expand All @@ -44,7 +93,13 @@ export function create(context: Rule.RuleContext): Rule.NodeListener {
return fixes;
},
},
],
);
}

context.report({
node: newExpr,
message: 'Expected a non-default error object to be thrown.',
suggest: suggestions,
});
}
},
Expand Down
Loading