logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Error Handling in JavaScript

author
Generated by
Abhishek Goyan

22/10/2024

JavaScript

Sign in to read full article

Handling errors effectively in JavaScript is not just about catching exceptions; it’s about understanding potential failure points, providing meaningful feedback, and maintaining a smooth user experience. In this blog, we’ll explore the different aspects of error handling in JavaScript, using vanilla-js and clear examples to help you grasp the concepts.

Understanding Errors in JavaScript

Errors in JavaScript can be broadly classified into two categories:

  1. Syntax Errors: These occur when the JavaScript engine encounters code that doesn’t follow the correct syntax, such as missing parentheses or commas.
  2. Runtime Errors: These happen when the code is syntactically correct but encounters an issue during execution, like trying to access a property of an undefined variable.

Example of Syntax Error:

// This will throw a syntax error const name = 'Alice' console.log(name // Missing closing parenthesis

Example of Runtime Error:

const person = null; console.log(person.name); // This will throw a runtime error: Cannot read properties of null

The try...catch Statement

The try...catch statement allows you to handle exceptions gracefully. Code that might throw an error is placed inside the try block, while the catch block handles the error.

Basic Usage Example:

try { let result = riskyOperation(); console.log(result); } catch (error) { console.error("An error occurred:", error.message); }

In this example, if riskyOperation() throws an error, the message will be logged without breaking the entire script.

Multiple catch Blocks

With the use of block-scoped variables, you can define multiple catch blocks by checking the type of error.

try { let data = JSON.parse("invalid json"); } catch (error) { if (error instanceof SyntaxError) { console.error("There was a syntax error:", error.message); } else { console.error("An unexpected error occurred:", error); } }

Finally Block

The finally statement can be used after try...catch to execute code regardless of an error being thrown. It’s useful for cleanup actions, such as closing database connections or releasing resources.

Example:

try { let result = riskyOperation(); console.log(result); } catch (error) { console.error("An error occurred:", error.message); } finally { console.log("Cleaning up!"); }

Throwing Custom Errors

You can create your own error types by extending the Error class. This gives you more control over error handling and allows for clearer error reporting.

Custom Error Class:

class CustomError extends Error { constructor(message) { super(message); this.name = "CustomError"; } } try { throw new CustomError("Something went wrong!"); } catch (error) { console.error(`${error.name}: ${error.message}`); }

Error Events

When working with the browser, it’s important to handle global errors as well. The window.onerror event allows developers to catch unhandled errors at the window level, providing a way to log them centrally.

Example of Global Error Handling:

window.onerror = function(message, source, lineno, colno, error) { console.error(`Error occurred: ${message} at ${source}:${lineno}:${colno}`); }; // Example triggering an error nonExistentFunction(); // This will be caught by the window.onerror event

Promises and Error Handling

When working with asynchronous code using promises, proper error handling can be achieved using .catch() or the async/await syntax with try...catch.

Example with Promises:

fetch("http://example.com/api/data") .then(response => { if (!response.ok) { throw new Error("Network response was not ok"); } return response.json(); }) .catch(error => { console.error("Fetch error:", error.message); });

Example with Async/Await:

async function fetchData() { try { const response = await fetch("http://example.com/api/data"); if (!response.ok) { throw new Error("Network response was not ok"); } const data = await response.json(); console.log(data); } catch (error) { console.error("Error fetching data:", error.message); } } fetchData();

By effectively using these error handling techniques in your JavaScript code, you can create resilient applications that handle potential failures gracefully while providing users with meaningful feedback. Familiarize yourself with these concepts and take your error handling skills to the next level!

Popular Tags

JavaScriptError HandlingVanilla JS

Share now!

Like & Bookmark!

Related Collections

  • JavaScript Mastery: From Basics to Advanced Techniques

    15/10/2024 | VanillaJS

  • JavaScript Interview Mastery: 20 Essential Concepts

    22/10/2024 | VanillaJS

  • JavaScript Coding Challenges for Interviews

    14/09/2024 | VanillaJS

Related Articles

  • Implementing a Debounce Function

    14/09/2024 | VanillaJS

  • Implementing a Simple Async Queue in JavaScript

    14/09/2024 | VanillaJS

  • JavaScript Performance Optimization Techniques

    22/10/2024 | VanillaJS

  • Understanding Prototypal Inheritance in Vanilla JavaScript

    22/10/2024 | VanillaJS

  • Understanding and Implementing Currying in JavaScript Functions

    14/09/2024 | VanillaJS

  • Build a Deep Clone Utility for Objects in JavaScript

    14/09/2024 | VanillaJS

  • Traverse JSON object to find paths leading to leaf nodes

    12/09/2024 | VanillaJS

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design