Onjsdev

Share


Custom JavaScript Error Classes: How to Throw and Catch Errors


By onjsdev

Nov 30th, 2023

In Javascript, developers primarily use the Error class to throw and catch errors in their code but in certain situations, it may not be efficient for error handling. Therefore, javascript allows you to create their own error classes so that errors thrown can have a different meaning.

Create A Custom Error Class In Js

A new custom error class is inheritied from the Error class so that custom error class can have arguments inherited such as message. Here is an example of custom error class called CustomError.

class CustomError extends Error {
  constructor(message) {
    super(message);
    this.code = 000;
  }
}

When you create a new instance with a message to throw the error, the message passes to the parent class's message argument with help of the super. As you realize we have extended the class by adding a new argument, code.

Throw and Catch Custom Error

In JavaScript, an error is thrown with the keyword throw and is caught with the try/catch blocks. let's create a scenario to show how to use these expressions with the custom error class.

try {
  let a = 4;
  let b = 0;

  if (b === 0) {
    // throw a custom error if b == 0
    throw new CustomError("not divisible by 0");
  } else {
    console.log(a / b);
  }
} catch (error) {
  // Catch the error
  if (error.code === 999 || error instanceof CustomError) {
    console.log("Custom Error:", error.message);
    // Custom Error: not divisible by 0
  }
}

Expand Error Classes

You can create the error class for certain errors. For Example, you can create different class for each http error as in the following example.

class BadReguest extends Error {
  constructor(message, isLog) {
    super(message);
    this.code = 400;
    this.isLog = isLog;
  }
}
class UnAuthroized extends Error {
  constructor(message, isLog) {
    super(message);
    this.code = 401;
    this.isLog = isLog;
  }
}

try {
  // Code that authentices a user

  throw new UnAuthroized("Invalid Credentials", false);
} catch (error) {
  if (error.isLog) {
    // log the login attemption
    // logToDatabase()
  } else {
    console.log(error.message);
    // Invalid Credentials
  }
}

Conclusion

In this article, we've cover how to create custom error classes in JavaScript which make error messages more descriptive and improve debugging easily.

Thank you for reading.