Skip to content

Commit 8f1d105

Browse files
liubinyisindresorhus
authored andcommitted
Add support for custom errors in the throw-new-error rule (#88)
1 parent c1c1799 commit 8f1d105

File tree

2 files changed

+56
-11
lines changed

2 files changed

+56
-11
lines changed

rules/throw-new-error.js

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,13 @@
11
'use strict';
22

3-
const errorTypes = [
4-
'Error',
5-
'EvalError',
6-
'RangeError',
7-
'ReferenceError',
8-
'SyntaxError',
9-
'TypeError',
10-
'URIError'
11-
];
3+
const customError = /^(?:[A-Z][a-z0-9]*)*Error$/;
124

135
const create = context => ({
146
ThrowStatement: node => {
157
const arg = node.argument;
168
const error = arg.callee;
179

18-
if (arg.type === 'CallExpression' && errorTypes.indexOf(error.name) !== -1) {
10+
if (arg.type === 'CallExpression' && customError.test(error.name)) {
1911
context.report({
2012
node,
2113
message: 'Use `new` when throwing an error.',

test/throw-new-error.js

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,15 @@ ruleTester.run('new-error', rule, {
1414
valid: [
1515
'throw new Error()',
1616
'new Error()',
17-
'throw new TypeError()'
17+
'throw new TypeError()',
18+
'throw new EvalError()',
19+
'throw new RangeError()',
20+
'throw new ReferenceError()',
21+
'throw new SyntaxError()',
22+
'throw new URIError()',
23+
'throw new CustomError()',
24+
'throw new FooBarBazError()',
25+
'throw new ABCError()'
1826
],
1927
invalid: [
2028
{
@@ -27,10 +35,55 @@ ruleTester.run('new-error', rule, {
2735
output: `throw new Error('foo')`,
2836
errors
2937
},
38+
{
39+
code: `throw CustomError('foo')`,
40+
output: `throw new CustomError('foo')`,
41+
errors
42+
},
43+
{
44+
code: `throw FooBarBazError('foo')`,
45+
output: `throw new FooBarBazError('foo')`,
46+
errors
47+
},
48+
{
49+
code: `throw ABCError('foo')`,
50+
output: `throw new ABCError('foo')`,
51+
errors
52+
},
53+
{
54+
code: `throw Abc3Error('foo')`,
55+
output: `throw new Abc3Error('foo')`,
56+
errors
57+
},
3058
{
3159
code: `throw TypeError()`,
3260
output: 'throw new TypeError()',
3361
errors
62+
},
63+
{
64+
code: `throw EvalError()`,
65+
output: 'throw new EvalError()',
66+
errors
67+
},
68+
{
69+
code: `throw RangeError()`,
70+
output: 'throw new RangeError()',
71+
errors
72+
},
73+
{
74+
code: `throw ReferenceError()`,
75+
output: 'throw new ReferenceError()',
76+
errors
77+
},
78+
{
79+
code: `throw SyntaxError()`,
80+
output: 'throw new SyntaxError()',
81+
errors
82+
},
83+
{
84+
code: `throw URIError()`,
85+
output: 'throw new URIError()',
86+
errors
3487
}
3588
]
3689
});

0 commit comments

Comments
 (0)