Skip to content

Commit

Permalink
fix(require-throws): arrow function expressions should check body o…
Browse files Browse the repository at this point in the history
…nly; fixes #597

`node.expression` is just a boolean with `ArrowFunctionExpression` (and `false` on `FunctionExpression`, `FunctionDeclaration`).

Also avoids reporting nested throw statements (which might not be invoked as the function executes).
  • Loading branch information
brettz9 committed Jul 1, 2020
1 parent c39fd75 commit e5387f1
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 2 deletions.
22 changes: 22 additions & 0 deletions README.md
Expand Up @@ -13210,6 +13210,18 @@ function quux () {
}
// Settings: {"jsdoc":{"tagNamePreference":{"throws":false}}}
// Message: Unexpected tag `@throws`
/**
*
*/
const itself = (b) => {
const a = () => {};
if (b) {
throw new Error('oops')
}
return a;
};
// Message: Missing JSDoc @throws declaration.
````
The following patterns are not considered problems:
Expand Down Expand Up @@ -13258,6 +13270,16 @@ function quux () {
throw new Error('err')
}
// Options: [{"exemptedBy":["type"]}]
/**
*
*/
const itself = (n) => n;
/**
* Not tracking on nested function
*/
const itself = () => () => {throw new Error('oops');};
````
Expand Down
5 changes: 3 additions & 2 deletions src/jsdocUtils.js
Expand Up @@ -614,17 +614,18 @@ const hasReturnValue = (node) => {
* Checks if a node has a throws statement.
*
* @param {object} node
* @param {boolean} innerFunction
* @returns {boolean}
*/
const hasThrowValue = (node) => {
const hasThrowValue = (node, innerFunction) => {
if (!node) {
return false;
}
switch (node.type) {
case 'FunctionExpression':
case 'FunctionDeclaration':
case 'ArrowFunctionExpression': {
return node.expression || hasThrowValue(node.body);
return !innerFunction && hasThrowValue(node.body, true);
}
case 'BlockStatement': {
return node.body.some((bodyNode) => {
Expand Down
36 changes: 36 additions & 0 deletions test/rules/assertions/requireThrows.js
Expand Up @@ -294,6 +294,26 @@ export default {
},
},
},
{
code: `
/**
*
*/
const itself = (b) => {
const a = () => {};
if (b) {
throw new Error('oops')
}
return a;
};
`,
errors: [
{
line: 2,
message: 'Missing JSDoc @throws declaration.',
},
],
},
],
valid: [
{
Expand Down Expand Up @@ -362,5 +382,21 @@ export default {
},
],
},
{
code: `
/**
*
*/
const itself = (n) => n;
`,
},
{
code: `
/**
* Not tracking on nested function
*/
const itself = () => () => {throw new Error('oops');};
`,
},
],
};

0 comments on commit e5387f1

Please sign in to comment.