Custom Error Classes
JS · Error Handlingsyntax
class CustomError extends Error {
constructor(message) {
super(message);
this.name = "CustomError";
}
}example
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
class NotFoundError extends Error {
constructor(resource, id) {
super(`${resource} with id ${id} not found`);
this.name = "NotFoundError";
this.resource = resource;
this.id = id;
}
}
try {
throw new ValidationError("email", "Invalid email format");
} catch (err) {
if (err instanceof ValidationError) {
console.log(`Field: ${err.field}, Message: ${err.message}`);
}
}output
"Field: email, Message: Invalid email format"Note Custom errors let you add context (which field, which resource) and enable precise catch handling with instanceof checks.