DEV Community

Cover image for Error Handling in JavaScript
Tanmay Agrawal
Tanmay Agrawal

Posted on

Error Handling in JavaScript

consider the following code

const url = 'https://jsonplaceholder.typicode.com/posts'
fetch(url).then(res=>res.json()).then(data=>console.log(data))
Enter fullscreen mode Exit fullscreen mode

Although the above code is so lean, what happens if there is a little mistake in the url ? what if we change from posts to post here. The error will not be catch in that case, So in order to handle it there is a better method to use the .catch and throw new Error('custom error message here!')

and to explain this consider the following code:

const getJson = function(url, errmsg){
  return fetch(url).then(res=>{
    if(!res.ok) throw new Error(errmsg)
    return res.json()
  })
}

getJson('https://jsonplaceholder.typicode.com/posts', 'something went wrong').then(data=>console.log(data)).catch(err=>console.log(err.message))
Enter fullscreen mode Exit fullscreen mode

Now this is the most simplified version, but here we have added the custom error message as 'something went wrong!' but as per out code we can add accurate messages here that will be catch at the end by the .catch block

We can also check the response text, if we see the res object in the above code there is a property called status, that contains 200 for OK and 404 for bad network, so we can also log the res.status with the custom message so that the error response is clear.

Example in below code, lets make a mistake in url and change posts to post

const getJson = function(url, errmsg){
  return fetch(url).then(res=>{
    if(!res.ok) throw new Error(`${res.status} : ${errmsg}`)
    return res.json()
  })
}

getJson('https://jsonplaceholder.typicode.com/post', 'something went wrong').then(data=>console.log(data)).catch(err=>console.log(err.message))

//Output:
//404: Something went wrong
Enter fullscreen mode Exit fullscreen mode

try{}catch{} Block

try{
//do something
}catch(err){
alert(err.message)
}
Enter fullscreen mode Exit fullscreen mode

This is a try catch block helpful to handle error, let us see a simple example

const posts = async function(){
  const res = await fetch('https://jsonplaceholder.typicode.com/posts')
  if(!res.ok) throw new Error('Something went wrong')
  const data = await res.json()
  return(data)

  //incase promise is rejected

};

(async function(){
  try{
    const post = await posts();
    console.log(post)
  }catch(err){
    console.log(err.message)
  }
})();
Enter fullscreen mode Exit fullscreen mode

In this example if the promise is rejected the error message is thrown, i,e, the condition when the response.ok is not true

Now consider the following code example

function divide(x, y) {
  try {
    if (y === 0) {
      throw new Error("Division by zero error");
    }
    return x / y;
  } catch (error) {
    console.log("Error caught:", error.message);
    // Handle the error
    return 0;
  } finally {
    console.log("Finally block always executed");
    // Perform cleanup tasks or resource deallocation
  }
}

console.log(divide(6, 2)); // Output: 3
console.log(divide(6, 0)); // Output: Error caught: Division by zero error, Finally block always executed, 0

Enter fullscreen mode Exit fullscreen mode

try: The try block is used to enclose the code that might throw an exception. If an exception occurs within the try block, the control is passed to the corresponding catch block.

catch: The catch block is used to handle the exception that was thrown within the try block. It allows you to define the actions to be taken when a specific type of error occurs.

finally: The finally block is always executed, regardless of whether an exception is thrown. It is commonly used for cleanup tasks, ensuring that certain actions are performed irrespective of the occurrence of an error.

Why error handling is important ?

Error handling is crucial in programming, including in JavaScript, because it ensures that applications can gracefully manage unexpected issues, maintain stability, and provide a better user experience. Here are several reasons why error handling is important:

  1. Preventing Application Crashes: Effective error handling prevents the application from crashing when unexpected issues or exceptions occur during runtime.

  2. Enhancing User Experience: Proper error handling helps create a better user experience by providing informative error messages or feedback, guiding users on how to proceed when errors occur.

  3. Identifying and Resolving Issues: Error handling facilitates the identification and debugging of issues by providing valuable information about the nature and location of errors, making it easier for developers to resolve them.

  4. Ensuring Application Stability: Handling errors in a controlled manner helps maintain the stability and reliability of the application, ensuring that it continues to function as intended even when unexpected situations arise.

  5. Protecting Data Integrity: Proper error handling protects the integrity of data by preventing data loss or corruption that may occur due to unhandled exceptions or errors.

  6. Maintaining Security: Effective error handling contributes to maintaining the security of the application by preventing potential vulnerabilities that could be exploited by malicious actors.

  7. Facilitating Maintenance and Upgrades: Implementing robust error handling practices makes the codebase more maintainable and enables easier future upgrades or modifications to the application.

By implementing comprehensive error handling practices, developers can build more robust, stable, and user-friendly applications, leading to improved user satisfaction and overall application reliability.

Top comments (2)

Collapse
 
artydev profile image
artydev • Edited

Thank you for the nice article

But I dont think testing if x == 0 deserves to be enclosed in a try catch.
Beware to not use try catch as a control flow.
Exceptions are exceptionals by definition

Regards

Collapse
 
tanmaycode profile image
Tanmay Agrawal

Thanks for your feedback, You are actually correct about your point that we cannot use the try catch as a control flow, and yes exceptions are exceptionals by definitions, and therefore the last example is a very clear one that divide by zero is an exceptional error, Although in practice it wont be done, but here it makes the reader think about the code and retains the concept more intuitively.