How to work with error handling in Javascript

terrythreatt

Terry Threatt

Posted on April 17, 2021

How to work with error handling in Javascript

In programming unintended side-effects called errors can and will happen in your code. Allowing these errors to be introduced to people that are using your programs is frowned upon and a very bad user experience.

Error Handling is the technique of smoothly handling these errors and providing useful information to a user.

Here are the important parts of error handling:

Try

The try block allows you to try an initial blog of code.


async function doWork() {

  try {
    let response = await fetch("www.worktobedone.com") 

    let work = await response.json()

    return work
  }

}
Enter fullscreen mode Exit fullscreen mode

Catch

The catch block allows you to catch an error from the initial blog of code.


async function doWork() {

  try {
    let response = await fetch("www.worktobedone.com") 

    let work = await response.json()

    return work
  } catch(error) {
     // Here we caught an error to alert
     alert(error)
  }

}
Enter fullscreen mode Exit fullscreen mode

Throw

The throw keyword allows you to control or create custom exceptions from your code.


async function doWork() {

  try {
    let response = await fetch("www.worktobedone.com") 

    let work = await response.json()

    return work
  } catch(error) {
     // Lets change the error output
     throw new Error(`Oops we found this error during work - ${error}`)
  }

}
Enter fullscreen mode Exit fullscreen mode

Finally

The finally block allows you to execute code regardless of errors in the try and catch blocks.


async function doWork() {

  try {
    let response = await fetch("www.worktobedone.com") 

    let work = await response.json()

    return work
  } catch(error) {
     throw new Error(`Oops we found this error during work - ${error}`)
  } finally {
   return "My work here is done."
  }

}
Enter fullscreen mode Exit fullscreen mode

Let's chat about error handling

This walkthrough showed the steps to using the try..catch...finally block to handle errors. If you enjoyed this post feel free to leave a comment about your thoughts and experiences handling errors in your code.

Happy Coding,
Terry Threatt

💖 💪 🙅 🚩
terrythreatt
Terry Threatt

Posted on April 17, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related