Error Handling In JavaScript
Tags: javascript, errors
Published: 2019-11-17 15:42:18

When running JavaScript code, many errors can occur. Wrong input, undefined variables,  functions, the incorrect syntax will cause mistakes. If we don't handle them, they will block further execution of the code and lead to poor user experience and frustration. In this article, we will take a quick look at how to handle occurring errors for easier debugging and meaningful information to the user.

## `try`, `catch` And `finally`

Most errors occur and require handling when dealing with user inputs or data from other sources, for example, reading and sending data to the server or running asynchronous code. If an error happens during the execution, JavaScript will stop and create an error object. It is called `throw an exception`.
Try-catch statement lets to check a defined code for errors in the `try` block, and if it detects one, it will skip the following statements and jumps to the `catch` block to handle the error. 

```jsx
try {
  // x is not defined in the scope and will throw an exception
  console.log(x)
  // this statement will be skipped
  console.log('Last block call');
} catch(error) {
  console.error(error);
}
```
In the example above, we try to execute two statements where the first one should log not defined variable `x`. JavaScript, by default, will throw an exception and jumps to the `catch` block. `catch` will hold the value of that exception. For easier debugging use `console.error` instead of `console.log`, because it will form the error message and add it to the list of errors generated by the page.
When using a try-catch, if an error will occur, only `try` block statements will stop executing. The code outside try-catch will not freeze and continue to run.

While try-catch always comes together, there's additional `finally` block, that will execute code whether or not the exception is thrown. You would usually use it to close the connection or stream, to fail elegantly by releasing the code in the block in case of errors.

```jsx
try {
  // ...
} catch(error) {
  // ...
} finally {
  closeConnection();
}
```

## `throw` Statement

`throw` statement lets you create custom error messages. When the statemente executes, a value must be specified, and it can be any type:

```jsx
throw 7; // Number type
throw 'Invalid string'; // String type
throw false; // Boolean type
throw { name: 'SyntaxError'; message: 'Unknown character' }; // Object type
throw new Error('Typo'); // Error object constructor
```
When using `throw` in the try-catch statement, the triggered `throw` exception value can be accessed in the `catch` block.
If the `throw` statement is not handled, for example, in the try-catch, it stops the JavaScript executions.

## `Error` Object

The `Error` object is built in JavaScript error constructor, which is called automatically when the error occurs or can be generated and thrown manually. It holds three properties: `name`, `message`, and `stack`.
When using a built-in `Error` object, it makes debugging more accessible, because it traces back the call stack until the thrown error, so you can see which line of code caused the problems.
Most auto generated thrown named errors are:
- `SyntaxError` - error made in the syntax, i.e. misplaced comma in the code
- `TypeError` - type connected error, i.e. run a method that type does not have `'str'.toFix()`
- `ReferenceError` - when referencing functions or variables that are not declared

To use a constructor, we call it with `new` variable and specify a message as an argument:

```jsx
try {
  throw new Error('Invalid input');
} catch(error) {
  console.error('Name:', error.name); // Name: Error
  console.error('Message:', error.message); // Message: Invalid input
}
```

## Conclusion

That's the basics of error handling in JavaScript. Error eventually will happen, and knowing how to manage them gracefully can make debugging more comfortable and lead to better user experience.