Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

Fix #4530: no-string-throw fixer creates syntax errors #4540

Merged
merged 8 commits into from Mar 31, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/rules/noStringThrowRule.ts
Expand Up @@ -73,10 +73,20 @@ function walk(ctx: Lint.WalkContext<void>): void {
if (isThrowStatement(node)) {
const { expression } = node;
if (expression !== undefined && isString(expression)) {
ctx.addFailureAtNode(node, Rule.FAILURE_STRING, [
const fix = [
Lint.Replacement.appendText(expression.getStart(sourceFile), "new Error("),
Lint.Replacement.appendText(expression.getEnd(), ")"),
]);
];

const hasWhitespaceAfterThrow = /^throw\s+/.test(node.getText());
JoshuaKGoldberg marked this conversation as resolved.
Show resolved Hide resolved
if (!hasWhitespaceAfterThrow) {
const token = node.getFirstToken() as ts.Node;
if (token !== undefined && token.kind === ts.SyntaxKind.ThrowKeyword) {
fix.push(Lint.Replacement.appendText(token.getEnd(), " "));
}
}

ctx.addFailureAtNode(node, Rule.FAILURE_STRING, fix);
}
}
return ts.forEachChild(node, cb);
Expand Down
24 changes: 24 additions & 0 deletions test/rules/no-string-throw/test.ts.fix
@@ -0,0 +1,24 @@
let a: never = () => throw new Error('bla');

let b: never = () => throw new Error('bla');

let c: never = () => throw new Error('string1' + 'string2' + 'string3');

let d: never = () => throw new Error('string' + 1);

let e: never = () => throw new Error('string1' + 1 + {});

let f: never = () => throw new Error(('string'));

let g: never = () => throw new Error(1 + 2 + ('string'));

// no warning because rule does not check for toString()
const one = 1;
let h: never = () => throw one.toString();

let i: never = () => throw new Error(`some template string`);

const someVariable = 123;
let j: never = () => throw new Error(`template with ${someVariable} string`);

throw new Error(('component requires CSS height property'));
3 changes: 3 additions & 0 deletions test/rules/no-string-throw/test.ts.lint
Expand Up @@ -28,3 +28,6 @@ let i: never = () => throw `some template string`;
const someVariable = 123;
let j: never = () => throw `template with ${someVariable} string`;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Throwing plain strings (not instances of Error) gives no stack traces]

throw('component requires CSS height property');
rrogowski marked this conversation as resolved.
Show resolved Hide resolved
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Throwing plain strings (not instances of Error) gives no stack traces]