Skip to content

Commit d9d1cfe

Browse files
Add additional error type-checking examples and use instanceof in later examples
1 parent aabbec1 commit d9d1cfe

File tree

1 file changed

+47
-3
lines changed

1 file changed

+47
-3
lines changed

1-js/10-error-handling/1-try-catch/article.md

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,9 @@ Of course, everything's possible! Programmers do make mistakes. Even in open-sou
355355
356356
In our case, `try..catch` is meant to catch "incorrect data" errors. But by its nature, `catch` gets *all* errors from `try`. Here it gets an unexpected error, but still shows the same `"JSON Error"` message. That's wrong and also makes the code more difficult to debug.
357357
358-
Fortunately, we can find out which error we get, for instance from its `name`:
358+
Fortunately, there are multiple ways to determine the type of error. Common methods are shown below.
359+
360+
Using its `name` property:
359361
360362
```js run
361363
try {
@@ -367,6 +369,48 @@ try {
367369
}
368370
```
369371
372+
Using its `constructor.name` property (read-only):
373+
374+
```js run
375+
try {
376+
user = { /*...*/ };
377+
} catch(e) {
378+
*!*
379+
alert(e.constructor.name); // "ReferenceError" for accessing an undefined variable
380+
*/!*
381+
}
382+
```
383+
384+
Comparing its `constructor` property to the specific error type:
385+
386+
```js run
387+
try {
388+
user = { /*...*/ };
389+
} catch(e) {
390+
*!*
391+
if (e.constructor === RefferenceError) {
392+
alert('e is a ReferenceError'); // "ReferenceError" for accessing an undefined variable
393+
}
394+
*/!*
395+
}
396+
```
397+
398+
Comparing its class type to another error type using the `instanceof` operator:
399+
400+
```js run
401+
try {
402+
user = { /*...*/ };
403+
} catch(e) {
404+
*!*
405+
if (e instanceof RefferenceError) {
406+
alert('e is an instance of ReferenceError'); // "ReferenceError" for accessing an undefined variable
407+
}
408+
*/!*
409+
}
410+
```
411+
412+
MDN suggests using the `constructor` property or `instanceof` operator in its [error examples](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Handling_a_specific_error).
413+
370414
The rule is simple:
371415
372416
**Catch should only process errors that it knows and "rethrow" all others.**
@@ -398,7 +442,7 @@ try {
398442
} catch(e) {
399443
400444
*!*
401-
if (e.name == "SyntaxError") {
445+
if (e instanceof SyntaxError) {
402446
alert( "JSON Error: " + e.message );
403447
} else {
404448
throw e; // rethrow (*)
@@ -425,7 +469,7 @@ function readData() {
425469
*/!*
426470
} catch (e) {
427471
// ...
428-
if (e.name != 'SyntaxError') {
472+
if (!(e instanceof SyntaxError)) {
429473
*!*
430474
throw e; // rethrow (don't know how to deal with it)
431475
*/!*

0 commit comments

Comments
 (0)