-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_errors.js
More file actions
70 lines (63 loc) · 2 KB
/
basic_errors.js
File metadata and controls
70 lines (63 loc) · 2 KB
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
/**
* The try statement allows you to define a block of code to be tested for errors while it is being executed.
* The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
*
*/
// The JavaScript statements try and catch come in pairs
// A ReferenceError occurs if you use (reference) a variable that does not exist.
let x = 5;
try {
x = y + 1;
} catch (err) {
console.log(err.name);
console.log(err); // ReferenceError: y is not defined
} finally {
console.log("must execute");
}
try {
printHello(x);
} catch (e) {
console.log("Error:", e); // Error: ReferenceError: printHello is not defined at
}
try {
x.toUpperCase();
} catch (e) {
console.log("Error:", e); // TypeError: x.toUpperCase is not a function
}
/**
* In JavaScript, the try statement is used to handle errors (also called exceptions) that may occur during code execution - without stopping the entire program.
*
* The try statement works together with catch.
* Sometimes it works with finally.
* And sometimes it works with throw.
* The finally block executes after the try and catch blocks, whether an error occurred or not. It is commonly used for cleanup tasks (e.g., closing files, stopping loaders, etc.).
*
*/
// throw:
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = 'ValidationError';
this.field = field;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ValidationError);
}
}
}
function validateAge(age) {
if (age < 18) {
throw new ValidationError('User must be at least 18 years old', 'age');
}
return "Voter";
}
try {
let check = validateAge(15);
// let check = validateAge(18);
console.log(check);
} catch (error) {
if (error instanceof ValidationError) {
console.error(`Custom Error: ${error.name} for field "${error.field}" - ${error.message}`);
} else {
console.log(error.name);
}
}