Error handling in Javascript

ProgrammingJun 2021

When a variable is mistyped, a curly brace isn’t closed, an array is called at an index greater than its length, in all these cases Javascript throws an error.

There are some tools that are useful to prevent and handle these errors. Starting with a top-level understanding of the errors themselves, the try-catch construct, the guard clause, and finally the Error object itself.

1. Error types

Type Errors are thrown when the program is trying to read something that doesn’t exist; when there is an attempt to change a constant; or when something that isn’t a function is called as such.

Reference Errors are thrown when a variable or function that does not exist is called by a program – reference because there is no reference to that variable or function.

Syntax Errors are thrown when something relating to Javascript’s syntax is mistyped – a missing parentheses in a function call, an extra pair of square brackets.

These are the most common errors, but there’s a more comprehensive list available on Mozilla’s website.

2. Try-Catch

The errors mentioned above will cause a program to crash during runtime. To prevent this from happening, I can encapsulate the fallible portion of the code inside a try clause and handle the error in the catch clause. This is most helpful especially when getting data from external sources such as user input or information coming in from an API.

When error occurs inside a try clause, the error information gets passed onto the catch clause as an argument that can then be fleshed out and printed onto the console without having to stop the program from running.

3. Guard Clause

Like the try-catch construct, the guard clause is a way to prevent fallible content from producing a runtime error and crashing the program. Useful, for example, at the start of a function to prevent invalid data from getting in without even having to run the rest of the function code.

4. Error Object

Finally, it’s worth pointing out that errors too are objects in Javascript. As a result, these can be instantiated by a programmer even when a program isn’t necessarily going to crash due to type, reference or syntax errors.

This is useful in instances similar to the case mentioned inthe guard clause. As a way to flag onto the console a potential error, or faulty data input. These errors are instantiated just like an object.

No items found.