Error Handling

throw operator

standard errors

1
2
3
4
5
// built-in constructors for standard errors
let error = new Error(message);
let error = new SyntaxError(message);
let error = new ReferenceError(message);
// ...

syntax

1
2
3
4
5
6
7
8
9
10
let json = '{ "age": 30 }'; // incomplete data

try {
let user = JSON.parse(json); // <-- no errors
if (!user.name) {
throw new SyntaxError("Incomplete data: no name"); // (*)
}
} catch(e) {
alert( "JSON Error: " + e.message ); // JSON Error: Incomplete data: no name
}

Rethrowing

  • catch should only process errors that it knows and “rethrow” all others (use instanceof)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let json = '{ "age": 30 }'; // incomplete data

try {
let user = JSON.parse(json);
if (!user.name) {
throw new SyntaxError("Incomplete data: no name");
}
blabla(); // unexpected error
} catch(e) {
if (e instanceof SyntaxError) {
alert( "JSON Error: " + e.message );
} else {
throw e; // rethrow (*)
}
}

try...catch...finally

  • finally is executed even with an explicit return.
  • finally is executed just before returns to the outer code.
1
2
3
4
5
6
7
try {
... try to execute the code ...
} catch(e) {
... handle errors ...
} finally {
... execute always ...
}

try...finally

  • Don’t want to handle errors.
  • But want to be sure that processes are finalized.

custom errors, extending Error

1
2
3
4
5
6
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}

Wrapping exceptions

  • a function handles low-level exceptions (PropertyRequiredError("age")), and creates higher-level errors (ReadError) instead of various low-level ones.
文章目录
  1. 1. throw operator
    1. 1.1. standard errors
    2. 1.2. syntax
    3. 1.3. Rethrowing
    4. 1.4. try...catch...finally
      1. 1.4.1. try...finally
  2. 2. custom errors, extending Error
    1. 2.1. Wrapping exceptions