extends Error
Builds on normal Error behavior.
Custom errors let an application name its own failure types and attach useful metadata.
class ValidationError extends Error {
name = "ValidationError";
}
throw new ValidationError("Title is required");
Errors & Debugging
A custom error usually extends Error and sets a distinct name. That lets catch blocks distinguish validation errors from network errors or programmer mistakes.
Custom errors can include fields such as code, field or details. Keep them small and predictable.
Use custom errors for repeated, meaningful failure categories. Do not create a new class for every one-off message.
Builds on normal Error behavior.
Identifies the custom error type.
Extra safe fields such as code or field.
Checks whether an error is a specific custom type.
Examples
try {
saveRecord(input);
} catch (error) {
if (error instanceof ValidationError) {
output.textContent = error.message;
} else {
throw error;
}
}
try {
saveRecord(input);
} catch (error) {
output.textContent = error.message;
}
// Programmer bugs now look like normal validation.
Code patterns
These examples focus on the debugging patterns you will reuse: safe parsing, throwing, custom error types, console inspection, breakpoints and async failure handling.
Extend Error and set a name.
class ValidationError extends Error {
name = "ValidationError";
}
Add safe structured detail.
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
Handle known custom errors differently.
if (error instanceof ValidationError) {
showMessage(error.message);
} else {
throw error;
}
Codes are useful for translation or UI mapping.
throw new ValidationError("Required value missing", "title");
Rules that matter
Debugging starts before something breaks. Clear error types, helpful messages and visible failure states make the code easier to repair.
Keep normal error behavior.
The name should describe the failure category.
Attach safe fields such as code or field.
Then rethrow unknown errors.
Use them for stable categories.
Do not expose secrets or internal details to users.
Production thinking
Custom errors let code handle expected application failures without hiding unexpected bugs.
Validation errors can map to clear field messages and status text.
Production systems can report custom error names and codes for better monitoring.
Build and render errors should identify failure categories clearly during publishing workflows.
Live code lab
The preview runs inside an isolated iframe. The JavaScript is placed inside the HTML editor for now, so every example stays together and remains easy to understand.
Mini assignment
Practice assignment
Try it yourself
Self-check
A JavaScript feature is not production-ready until you know how it fails and how you will inspect that failure.