-
Notifications
You must be signed in to change notification settings - Fork 0
/
DOCS_JS_ErrorHandling
71 lines (65 loc) · 2.04 KB
/
DOCS_JS_ErrorHandling
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#sample Handling of Specific Errors
try {
foo.bar();
} catch (e) {
if (e instanceof EvalError) {
console.error(`${e.name}: ${e.message}`);
} else if (e instanceof RangeError) {
console.error(`${e.name}: ${e.message}`);
}
// etc.
else {
// If none of our cases matched leave the Error unhandled
throw e;
}
}
# Differentiate between similar errors
Sometimes a block of code can fail for reasons that require different handling, but which throw very similar errors (i.e. with the same type and message).
If you don't have control over the original errors that are thrown, one option is to catch them and throw new Error objects that have more specific messages. The original error should be passed to the new Error in the constructor's options parameter as its cause property. This ensures that the original error and stack trace are available to higher-level try/catch blocks.
function doFailAnotherWay()
{
throw RangeError;
}
function handleFailAnotherWay(error)
{
console.log("Handling RangeError Raised Exception" + error);
}
function doFailSomeWay()
{
throw SyntaxError;
}
function handleFailSomeWay(error)
{
console.log("Handling SyntaxError Raised Exception" + error);
}
function doWork() {
try {
doFailSomeWay();
} catch (err) {
throw new Error("Failed in some way", { cause: err });
}
try {
doFailAnotherWay();
} catch (err) {
throw new Error("Failed in another way", { cause: err });
}
}
try {
doWork();
} catch (err) {
switch (err.message) {
case "Failed in some way":
handleFailSomeWay(err.cause);
break;
case "Failed in another way":
handleFailAnotherWay(err.cause);
break;
}
}
finally()
{
// check if an error occurred and if so gracefully exit
}
##################### OUPUTTING ERRORS ##################333
use: console.error("error message")
When logging errors to the console inside a catch block, using console.error() rather than console.log() is advised for debugging. It formats the message as an error, and adds it to the list of error messages generated by the page.