mirror of
https://github.com/nodejs/node.git
synced 2025-05-09 07:27:32 +00:00

This adds an ESLint rule to enforce the use of `assert.ifError(err)` instead of `if (err) throw err;` in tests. PR-URL: https://github.com/nodejs/node/pull/10671 Ref: https://github.com/nodejs/node/pull/10543 Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: Rich Trott <rtrott@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Gibson Fahnestock <gibfahn@gmail.com> Reviewed-By: Michal Zasso <targos@protonmail.com>
43 lines
1.1 KiB
JavaScript
43 lines
1.1 KiB
JavaScript
/**
|
|
* @fileoverview Prohibit the `if (err) throw err;` pattern
|
|
* @author Teddy Katz
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
module.exports = {
|
|
create(context) {
|
|
const sourceCode = context.getSourceCode();
|
|
|
|
function hasSameTokens(nodeA, nodeB) {
|
|
const aTokens = sourceCode.getTokens(nodeA);
|
|
const bTokens = sourceCode.getTokens(nodeB);
|
|
|
|
return aTokens.length === bTokens.length &&
|
|
aTokens.every((token, index) => {
|
|
return token.type === bTokens[index].type &&
|
|
token.value === bTokens[index].value;
|
|
});
|
|
}
|
|
|
|
return {
|
|
IfStatement(node) {
|
|
const firstStatement = node.consequent.type === 'BlockStatement' ?
|
|
node.consequent.body[0] :
|
|
node.consequent;
|
|
if (
|
|
firstStatement &&
|
|
firstStatement.type === 'ThrowStatement' &&
|
|
hasSameTokens(node.test, firstStatement.argument)
|
|
) {
|
|
context.report({
|
|
node: firstStatement,
|
|
message: 'Use assert.ifError({{argument}}) instead.',
|
|
data: {argument: sourceCode.getText(node.test)}
|
|
});
|
|
}
|
|
}
|
|
};
|
|
}
|
|
};
|