Skip to content

Errors in Javascript

Errors in JavaScript are runtime exceptions that disrupt the normal flow of code execution. Understanding how to handle and manage these errors is crucial for writing robust and reliable JavaScript applications. Here’s a detailed discussion on errors in JavaScript:

Types of Errors

JavaScript has several types of built-in errors:

  1. SyntaxError: Thrown when there is a syntax error in the code.

try {

    eval(‘foo bar’); // Invalid syntax

} catch (e) {

    console.log(e instanceof SyntaxError); // true

}

  • ReferenceError: Thrown when a non-existent variable is referenced.

try {

    console.log(nonExistentVariable); // Variable does not exist

} catch (e) {

    console.log(e instanceof ReferenceError); // true

}

  • TypeError: Thrown when a value is not of the expected type.

try {

    null.f(); // null is not an object

} catch (e) {

    console.log(e instanceof TypeError); // true

}

  • RangeError: Thrown when a numeric value is out of its valid range.

try {

    let arr = new Array(-1); // Invalid array length

} catch (e) {

    console.log(e instanceof RangeError); // true

}

  • URIError: Thrown when there is an error in URI handling functions like decodeURIComponent or encodeURIComponent.

try {

    decodeURIComponent(‘%’); // Malformed URI sequence

} catch (e) {

    console.log(e instanceof URIError); // true

}

  • EvalError: Thrown when there is an error in the eval() function.

try {

    throw new EvalError(‘EvalError example’);

} catch (e) {

    console.log(e instanceof EvalError); // true

}

Handling Errors

1. Try…Catch Block

The try…catch statement allows you to test a block of code for errors and handle them gracefully.

try {

    // Code that may throw an error

    let result = riskyOperation();

    console.log(result);

} catch (error) {

    // Code to handle the error

    console.log(‘An error occurred:’, error.message);

} finally {

    // Code that will always run, regardless of error

    console.log(‘Cleanup if necessary’);

}

2. Throwing Errors

You can manually throw errors using the throw statement, allowing custom error handling.

function checkAge(age) {

    if (age < 18) {

        throw new Error(‘Age must be at least 18’);

    }

    return ‘Access granted’;

}

try {

    console.log(checkAge(15)); // This will throw an error

} catch (e) {

    console.log(e.message); // “Age must be at least 18”

}

Custom Error Types

JavaScript allows you to create custom error types by extending the built-in Error class.

class CustomError extends Error {

    constructor(message) {

        super(message);

        this.name = ‘CustomError’;

    }

}

try {

    throw new CustomError(‘This is a custom error’);

} catch (e) {

    console.log(e instanceof CustomError); // true

    console.log(e.message); // “This is a custom error”

}

Error Properties

Error objects have several properties that provide more information about the error:

  • name: The name of the error (e.g., ‘ReferenceError’, ‘TypeError’).
  • message: A human-readable description of the error.
  • stack: A stack trace that provides information about where the error occurred.

try

{

    let obj;

    obj.method(); // This will throw a TypeError

} catch (e) {

    console.log(e.name); // “TypeError”

    console.log(e.message); // “Cannot read property ‘method’ of undefined”

    console.log(e.stack); // Stack trace

}

Promises and Async/Await

Handling errors in asynchronous code is slightly different. Promises provide a .catch method, and async/await can be used with try…catch for error handling.

Using Promises

fetch(‘https://api.example.com/data’)

    .then(response => response.json())

    .then(data => console.log(data))

    .catch(error => console.log(‘An error occurred:’, error));

Using Async/Await

async function fetchData() {

    try {

        let response = await fetch(‘https://api.example.com/data’);

        let data = await response.json();

        console.log(data);

    } catch (error) {

        console.log(‘An error occurred:’, error);

    }

}

fetchData();

Summary

  • Types of Errors: JavaScript has several built-in error types like SyntaxError, ReferenceError, TypeError, etc.
  • Handling Errors: Use try…catch blocks to handle errors gracefully.
  • Throwing Errors: Use the throw statement to generate custom errors.
  • Custom Error Types: Extend the Error class to create custom error types.
  • Error Properties: Use properties like name, message, and stack to get more information about errors.
  • Asynchronous Errors: Handle errors in promises with .catch and in async/await with try…catch.

Understanding and managing errors effectively is crucial for writing robust JavaScript applications. Proper error handling helps in debugging, maintaining code quality, and providing a better user experience.