I’ve noticed error handling is often an afterthought in javascript I’ve seen. Good error handling can make your javascript more easier to debug, more efficient and more robust.
A less than optimal way to catch errors
A less optimal way to catch errors and notify the caller is by returning a special value such as undefined, or a boolean or whatever. Below is an example.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
This works great, but it means that everytime you call doubleYourAge
, you are forced to perform a check. This can be inefficient if you’re calling the function multiple times in your scripts.
Throwing and catching basic errors
A better way, but still not the best, is to throw an error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
The above code is better than the first example, it only needs to run the error handling code if an error actually occurs, and no checking needs to be done everytime the funciton is called. Depending on your use-case, you might want to catch specific erros and conditions. This is where selective catching of errors is useful.
Selective catching of errors
The script below does the same thing as above, only this time, we instantiate Error objects which allows us to:
- throw specific errors
- catch and handle each error condition individually.
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 |
|
There you go, simple, easy error handling with javascript.