Javascript — Error handling

Why error handling? While we are executing code, we might encounter lots of errors including javascript error, system error or API returned error. Once the error occurs and we didn’t handle it properly, it will terminate code execution. In some scenarios we don’t want our code to terminate, we should use error handling to catch the error and make sure we continue executing our code.

without error handling, code terminates at line 1

with error handling, code will execute till the end of the script

In the previous article, I have explained the difference between callback, promise, async/await (https://toddypet.medium.com/javascript-asynchronous-programming-77f8899cd143). This article is created to handle a more complex scenario on asynchronous error handling.

The outline for this article:

  1. Basic error handling
  2. Promise error handling
  3. Async/await error handling

Basic Error handling

For the basic error handling, if start with the try-catch statement:

Try: allows you to define the code you want to execute. If at any line in this block’s execution have errors, it will be handle in catch

Catch: allows you to define a block of code to be executed if any error in try block

try {} catch(error){}

Throw: You can also have better control of the program flow by manually throw errors in try block. You can throw a String, Number, Boolean or an Object

Finally: finally statement is optional, if will execute code after try and catch regardless of the result

it runs when no errors in try block

it also runs if any error been caught in catch block

Promise error handling

Now, let’s see how error handling works in promise.

Promise chain handles error in an elegant way. As long as at any step in the chain throws errors, it will jump to catch block to handle it.

When both taskOne, taskTwo pass:

When taskOne fail, it skip taskTwo chain and jump to catch:

When taskTwo fail, it will jump to catch:

You can also analyse and rethrow an error in next catch block

Async/Await error handling

we often use try..catch block to handle error for async/await.

Once Task 1 fail, it jumps to catch block and will not run taskTwo

After run taskOne, when taskTwo fail, it will jump to catch to catch the error

If you don’t have try catch block in async function. Because Async function it self also return promise, you can use a .catch after async function to handle error

Hello, I am Heidi. I started this medium blog to post all of the note I have when I am learning new things. Hope you find it useful as well:)