]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/rules/no-throw-literal.md
ecb19edd16ea88e9822486cab4adcdde7a536f9f
[pve-eslint.git] / eslint / docs / rules / no-throw-literal.md
1 # Restrict what can be thrown as an exception (no-throw-literal)
2
3 It 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.
4 The fundamental benefit of `Error` objects is that they automatically keep track of where they were built and originated.
5
6 This 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.
7
8 ## Rule Details
9
10 This rule is aimed at maintaining consistency when throwing exception by disallowing to throw literals and other expressions which cannot possibly be an `Error` object.
11
12 Examples of **incorrect** code for this rule:
13
14 ```js
15 /*eslint no-throw-literal: "error"*/
16 /*eslint-env es6*/
17
18 throw "error";
19
20 throw 0;
21
22 throw undefined;
23
24 throw null;
25
26 var err = new Error();
27 throw "an " + err;
28 // err is recast to a string literal
29
30 var err = new Error();
31 throw `${err}`
32
33 ```
34
35 Examples of **correct** code for this rule:
36
37 ```js
38 /*eslint no-throw-literal: "error"*/
39
40 throw new Error();
41
42 throw new Error("error");
43
44 var e = new Error("error");
45 throw e;
46
47 try {
48 throw new Error("error");
49 } catch (e) {
50 throw e;
51 }
52 ```
53
54 ## Known Limitations
55
56 Due to the limits of static analysis, this rule cannot guarantee that you will only throw `Error` objects.
57
58 Examples of **correct** code for this rule, but which do not throw an `Error` object:
59
60 ```js
61 /*eslint no-throw-literal: "error"*/
62
63 var err = "error";
64 throw err;
65
66 function foo(bar) {
67 console.log(bar);
68 }
69 throw foo("error");
70
71 throw new String("error");
72
73 var foo = {
74 bar: "error"
75 };
76 throw foo.bar;
77 ```