Wednesday, 19 February 2025

How to define custom errors in JavaScript?

In JavaScript, you can define custom errors by creating a new error class that extends the built-in Error class. This allows you to throw more specific errors tailored to your application's needs. Defining custom error classes helps in handling specific error types differently, making your code more readable and maintainable. Let's walk through the process of defining a custom error in JavaScript.

Why Define Custom Errors?

1.   Specificity: Custom errors provide more specific error messages and types, making debugging easier.

2.   Error Handling: They allow for more fine-grained error handling. For example, you can catch a specific type of error and handle it differently than a general error.

3.   Clarity: Custom errors make the code more readable and intentions clear, as you can convey what went wrong using meaningful error names.

 

Defining a Custom Error

To define a custom error, you typically create a new class that extends the Error class.

 

Example

class ValidationError extends Error {
    constructor(message) {
        super(message);
        this.name = this.constructor.name;
        Error.captureStackTrace(this, this.constructor);
    }
}

custom-error.js

class ValidationError extends Error {
    constructor(message) {
        super(message);
        this.name = this.constructor.name;
        Error.captureStackTrace(this, this.constructor);
    }
}

function validateUserInput(input) {
    if (input.length < 5) {
        throw new ValidationError("Input must be at least 5 characters long.");
    }
    console.log("Input is valid.");
}

try {
    validateUserInput("abc"); // This will throw a ValidationError
} catch (error) {
    if (error instanceof ValidationError) {
        console.log(`Validation Error: ${error.message}`);
    } else {
        console.log(`General Error: ${error.message}`);
    }
}

Output

Validation Error: Input must be at least 5 characters long

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment