refactor: Remove usless catch blocks, and add a linting rule to prevent them (no-changelog) (#12730)

This commit is contained in:
कारतोफ्फेलस्क्रिप्ट™
2025-01-20 18:20:04 +01:00
committed by GitHub
parent 4ee4552b0e
commit 202da76380
17 changed files with 220 additions and 242 deletions

View File

@@ -172,6 +172,49 @@ module.exports = {
},
},
'no-useless-catch-throw': {
meta: {
type: 'problem',
docs: {
description: 'Disallow `try-catch` blocks where the `catch` only contains a `throw error`.',
recommended: 'error',
},
messages: {
noUselessCatchThrow: 'Remove useless `catch` block.',
},
fixable: 'code',
},
create(context) {
return {
CatchClause(node) {
if (
node.body.body.length === 1 &&
node.body.body[0].type === 'ThrowStatement' &&
node.body.body[0].argument.type === 'Identifier' &&
node.body.body[0].argument.name === node.param.name
) {
context.report({
node,
messageId: 'noUselessCatchThrow',
fix(fixer) {
const tryStatement = node.parent;
const tryBlock = tryStatement.block;
const sourceCode = context.getSourceCode();
const tryBlockText = sourceCode.getText(tryBlock);
const tryBlockTextWithoutBraces = tryBlockText.slice(1, -1).trim();
const indentedTryBlockText = tryBlockTextWithoutBraces
.split('\n')
.map((line) => line.replace(/\t/, ''))
.join('\n');
return fixer.replaceText(tryStatement, indentedTryBlockText);
},
});
}
},
};
},
},
'no-skipped-tests': {
meta: {
type: 'problem',