Beginner's guide to handle errors in JavaScript

Beginner's guide to handle errors in JavaScript

One thing all the developers know for sure is that things don't always go well in our programs. In particular we might want to stop the program or inform the user midway about something that went wrong. In such cases we write our code to report an error, or the code reports the error itself.

Errors are a part of programming. When we encounter an error it makes no sense to execute the rest of the code, so we try to elegantly handle the error. The interpreter checks for error handling or exception handling code when it gets an error, if no such code is found it prints the error in the browser console and terminates the execution of the rest of the code. So the question is what is the proper way of handling exceptions.

Exceptions can be handled in two ways:

  • Throw an Exception - If you encounter an error that cant be handled meaningfully at run time, the correct way is to throw it.

throw.png

  • Catch an Exception - If you encounter an error unexpectedly, the best and most meaningful way to handle it is to place the code inside the try-catch block.

catch.png

Throw an Exception

Exceptions are like an elevator going up: once you throw one, it bubbles up in the program stack, unless it is caught somewhere.

Consider the following code: throw.png

When executed the above code will give the following error:

error.png

We can see at which function did we get an error and also exactly at which line did we get one.

This report of the error is called as stack trace, and is very helpful while finding the root cause of the error.

On examining the above stack trace, we can conclude that:

  • someFunction(4) was called at line no 9.
  • someFunction() threw an error at line no 3.

If nothing is done by the developer's to catch errors, the code might crash. So its always advised to catch errors for smooth functioning of the code.

Catch an exception

Since we now know the importance of catching errors, lets look at the ways to catch them so our code is not crashed due to them.

try-catch

This is the most simplest and efficient way to catch errors. It has two main blocks: try and then catch:

handle.png

We add the code that might generate errors inside the try block, if the code in try block contains errors the catch block will be executed. In case no errors are generated in try block, the catch block will not be executed.

try-catch block can be used in places where we are not sure whether the code will execute seamlessly every time. One thing to keep note of is that we cant catch syntax errors with try-catch method.

try-catch-finally

The try-catch-finally block work the same as try-catch blocks, the only difference is that a finally block is added at the end. The finally block will execute on every run irrespective of whether we get an error or not.

finally.png

try-catch or try-catch-finally block only works with synchronous code, In case of asynchronous code it is possible that our try-catch blocks will be executed before the asynchronous code finishes its execution.

Asynchronous error handling

Let us look at the ways by which we can handle errors asynchronous code blocks in JavaScript.

Callback functions

A callback function generally looks like this: callback.png We usually receive two parameters as seen above err and result. If there is any error we the value of err will be that of the error and we can throw the error.

It should be noted that we check if any error is present before accessing the value of result, and proper if-else blocks are maintained for the same.

Promises

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

A promise is in either pending, fulfilled or rejected status. A pending promise is either fulfilled with a value or rejected with an error. We can have a look at an example below:

promise.png

If the promise is rejected it will go to the catch block and if it is fulfilled it will go inside then block.

The promise is a better option than callback but for bigger codebases it is quite difficult to understand the flow. So there is a better way which is async-await, which allows us to handle errors asynchronous code in a synchronous way.

async.png

Multiple errors can be caught by a single try-catch-await block which is complicated if we use any other options like Promise.

We have covered most of the ways to handle error in JavaScript from simple synchronous to advanced asynchronous code. Errors from Synchronous code are quite simple and straight forward to handle whereas the ones from Asynchronous code can be tricky at times.

Errors and Exceptions are a part of a developer's journey and you will encounter errors most of the time you sit down to code. You cant write a error free code, the best you can do is be prepared for errors to come and handle them at the right time.

I hope after reading this you will be able to identify different situations that you may face during coding and catch errors correctly.

Thanks for Reading. Happy Learning!