TL;DR
To create custom error objects in JavaScript, you can extend the built-in Error
class. This allows you to add custom properties and methods to your error objects. Here's a quick example:
class CustomError extends Error {
constructor(message) {
super(message);
this.name = 'CustomError';
}
}
try {
throw new CustomError('This is a custom error message');
} catch (error) {
console.log(error.name);
console.log(error.message);
}
How can you create custom error objects?
Extending the Error
class
To create a custom error object, you can extend the built-in Error
class. This allows you to inherit the properties and methods of the Error
class while adding your own custom properties and methods.
class CustomError extends Error {
constructor(message) {
super(message);
this.name = 'CustomError';
}
}
Adding custom properties
You can add custom properties to your custom error class to provide more context about the error.
class CustomError extends Error {
constructor(message, errorCode) {
super(message);
this.name = 'CustomError';
this.errorCode = errorCode;
}
}
try {
throw new CustomError('This is a custom error message', 404);
} catch (error) {
console.log(error.name);
console.log(error.message);
console.log(error.errorCode);
}
Custom methods
You can also add custom methods to your custom error class to handle specific error-related logic.
class CustomError extends Error {
constructor(message, errorCode) {
super(message);
this.name = 'CustomError';
this.errorCode = errorCode;
}
logError() {
console.error(`${this.name} [${this.errorCode}]: ${this.message}`);
}
}
try {
throw new CustomError('This is a custom error message', 404);
} catch (error) {
error.logError();
}
Using instanceof
to check for custom errors
You can use the instanceof
operator to check if an error is an instance of your custom error class.
try {
throw new CustomError('This is a custom error message', 404);
} catch (error) {
if (error instanceof CustomError) {
console.log('Caught a CustomError');
} else {
console.log('Caught a different type of error');
}
}
Further reading