How do you create a new Error object in JavaScript?

In JavaScript, you can create a new Error object using the Error constructor function. The Error constructor takes an optional message parameter which can be used to specify a custom error message.

Here’s an example of how to create a new Error object with a custom message:

const errorMessage = "This is a custom error message";
const error = new Error(errorMessage);

console.log(error.message); // "This is a custom error message"

In this example, we create a new variable errorMessage and assign it the value of our custom error message. Then we create a new Error object using the new keyword and pass in the errorMessage as an argument. Finally, we log the message property of the error object to the console, which should output our custom error message.

You can also create a new Error object without specifying a custom error message:

const error = new Error();

console.log(error.message); // "Error"

In this example, we create a new Error object without passing in any arguments. The message property of the error object will default to the string "Error".

You can also create your own custom error types by extending the Error class. Here’s an example of how to create a custom ValidationError class that extends the Error class:

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

const errorMessage = "Invalid input";
const error = new ValidationError(errorMessage);

console.log(error.name); // "ValidationError"
console.log(error.message); // "Invalid input"
console.log(error instanceof Error); // true
console.log(error instanceof ValidationError); // true

In this example, we define a new ValidationError class that extends the Error class. The constructor function of the ValidationError class takes a message parameter which is passed to the super() method to set the message property of the error object. We also set the name property of the error object to "ValidationError".

Then we create a new ValidationError object with our custom error message, and log the name, message, and instanceof properties of the error object to the console. The instanceof operator returns true for both Error and ValidationError, indicating that the ValidationError class inherits from the Error class.

You can also create custom error objects with additional properties or methods by adding them to the custom error class.

For example, let’s add a validationErrors property to our ValidationError class:

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

const validationErrors = { username: "Invalid username" };
const errorMessage = "Validation failed";
const error = new ValidationError(errorMessage, validationErrors);

console.log(error.validationErrors); // { username: "Invalid username" }

In this example, we modify the ValidationError class to take an additional validationErrors parameter in the constructor function. We set this parameter as a property of the error object, so that we can access it later.

Then we create a new ValidationError object with our custom error message and validation errors, and log the validationErrors property of the error object to the console.

You can also create custom error classes by extending the Error class and adding additional properties or methods. Custom error classes can be useful for creating more specific error types that are easier to handle and differentiate between different types of errors that may occur in your code.

For example:

class HTTPError extends Error {
  constructor(statusCode, message) {
    super(message);
    this.name = "HTTPError";
    this.statusCode = statusCode;
  }

  getErrorDetails() {
    return {
      statusCode: this.statusCode,
      message: this.message,
      timestamp: new Date().toISOString(),
    };
  }
}

const errorMessage = "Not Found";
const error = new HTTPError(404, errorMessage);

console.log(error.statusCode); // 404
console.log(error.message); // "Not Found"
console.log(error.getErrorDetails()); // { statusCode: 404, message: "Not Found", timestamp: "2023-04-30T00:00:00.000Z" }

In this example, we create a new HTTPError class that extends the Error class. We add an additional statusCode property to the error object and a getErrorDetails() method that returns an object containing the error details.

Then we create a new HTTPError object with a custom status code and error message, and log the statusCode, message, and getErrorDetails() output to the console.

By creating custom error classes with additional properties and methods, you can create more informative error messages that include additional details about the error, such as the error type, status code, and timestamp.

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: