UNPKG

2.51 kBMarkdownView Raw
1# `no-throw-literal`
2
3Disallow throwing literals as exceptions.
4
5It is considered good practice to only `throw` the `Error` object itself or an object using the `Error` object as base objects for user-defined exceptions.
6The fundamental benefit of `Error` objects is that they automatically keep track of where they were built and originated.
7
8This rule restricts what can be thrown as an exception. When it was first created, it only prevented literals from being thrown (hence the name), but it has now been expanded to only allow expressions which have a possibility of being an `Error` object. With the `allowThrowingAny` and `allowThrowingUnknown`, it can be configured to only allow throwing values which are guaranteed to be an instance of `Error`.
9
10## Rule Details
11
12This rule is aimed at maintaining consistency when throwing exception by disallowing to throw literals and other expressions which cannot possibly be an `Error` object.
13
14Examples of code for this rule:
15
16<!--tabs-->
17
18### ❌ Incorrect
19
20```ts
21/*eslint @typescript-eslint/no-throw-literal: "error"*/
22
23throw 'error';
24
25throw 0;
26
27throw undefined;
28
29throw null;
30
31const err = new Error();
32throw 'an ' + err;
33
34const err = new Error();
35throw `${err}`;
36
37const err = '';
38throw err;
39
40function err() {
41 return '';
42}
43throw err();
44
45const foo = {
46 bar: '',
47};
48throw foo.bar;
49```
50
51### ✅ Correct
52
53```ts
54/*eslint @typescript-eslint/no-throw-literal: "error"*/
55
56throw new Error();
57
58throw new Error("error");
59
60const e = new Error("error");
61throw e;
62
63try {
64 throw new Error("error");
65} catch (e) {
66 throw e;
67}
68
69const err = new Error();
70throw err;
71
72function err() {
73 return new Error();
74}
75throw err();
76
77const foo = {
78 bar: new Error();
79}
80throw foo.bar;
81
82class CustomError extends Error {
83 // ...
84};
85throw new CustomError();
86```
87
88## How to Use
89
90```jsonc
91{
92 // note you must disable the base rule as it can report incorrect errors
93 "no-throw-literal": "off",
94 "@typescript-eslint/no-throw-literal": ["error"]
95}
96```
97
98### Options
99
100```jsonc
101{
102 "@typescript-eslint/no-throw-literal": [
103 "error",
104 {
105 "allowThrowingAny": true, // Default is to allow throwing values of type any
106 "allowThrowingUnknown": true // Default is to allow throwing values of type unknown
107 }
108 ]
109}
110```
111
112---
113
114<sup>
115
116Taken with ❤️ [from ESLint core](https://github.com/eslint/eslint/blob/main/docs/rules/no-throw-literal.md)
117
118</sup>
119
120## Attributes
121
122- Configs:
123 - [ ] ✅ Recommended
124 - [x] 🔒 Strict
125- [ ] 🔧 Fixable
126- [x] 💭 Requires type information