Skip to content

Commit

Permalink
catch-error-name: Use simple selector (#2112)
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker committed May 16, 2023
1 parent 47397f7 commit 95e551d
Showing 1 changed file with 31 additions and 24 deletions.
55 changes: 31 additions & 24 deletions rules/catch-error-name.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,35 @@
const {findVariable} = require('@eslint-community/eslint-utils');
const avoidCapture = require('./utils/avoid-capture.js');
const {renameVariable} = require('./fix/index.js');
const {matches, methodCallSelector} = require('./selectors/index.js');
const {isMethodCall} = require('./ast/index.js');

const MESSAGE_ID = 'catch-error-name';
const messages = {
[MESSAGE_ID]: 'The catch parameter `{{originalName}}` should be named `{{fixedName}}`.',
};

const selector = matches([
// `try {} catch (foo) {}`
[
'CatchClause',
' > ',
'Identifier.param',
].join(''),
// - `promise.then(…, foo => {})`
// - `promise.then(…, function(foo) {})`
// - `promise.catch(foo => {})`
// - `promise.catch(function(foo) {})`
[
matches([
methodCallSelector({method: 'then', argumentsLength: 2}),
methodCallSelector({method: 'catch', argumentsLength: 1}),
]),
' > ',
':matches(FunctionExpression, ArrowFunctionExpression).arguments:last-child',
' > ',
'Identifier.params:first-child',
].join(''),
]);
// - `promise.then(…, foo => {})`
// - `promise.then(…, function(foo) {})`
// - `promise.catch(foo => {})`
// - `promise.catch(function(foo) {})`
const isPromiseCatchParameter = node =>
(node.parent.type === 'FunctionExpression' || node.parent.type === 'ArrowFunctionExpression')
&& node.parent.params[0] === node
&& (
isMethodCall(node.parent.parent, {
method: 'then',
argumentsLength: 2,
optionalCall: false,
optionalMember: false,
})
|| isMethodCall(node.parent.parent, {
method: 'catch',
argumentsLength: 1,
optionalCall: false,
optionalMember: false,
})
)
&& node.parent.parent.arguments.at(-1) === node.parent;

/** @param {import('eslint').Rule.RuleContext} context */
const create = context => {
Expand All @@ -50,7 +50,14 @@ const create = context => {
|| name.endsWith(expectedName.charAt(0).toUpperCase() + expectedName.slice(1));

return {
[selector](node) {
Identifier(node) {
if (
!(node.parent.type === 'CatchClause' && node.parent.param === node)
&& !isPromiseCatchParameter(node)
) {
return;
}

const originalName = node.name;

if (
Expand Down

0 comments on commit 95e551d

Please sign in to comment.