JavaScript
Create an application-specific Error subclass
Subclass Error when callers need to distinguish a known application failure from unrelated exceptions. Give it a meaningful name and retain a useful message for logs or user-facing handling.
Worked example
Node.js example · save as example.mjs and run node example.mjs
class InputError extends Error {
constructor(message) {
super(message);
this.name = "InputError";
}
}
try { throw new InputError("A filename is required"); }
catch (error) { console.log(error instanceof InputError, error.message); }How it works
Instance checking lets the catch block choose a deliberate response to invalid input while allowing unexpected errors to remain visible. Inheriting from Error preserves standard error behavior such as a message and a diagnostic stack in common runtimes.
Limits and mistakes
Do not expose sensitive internal details merely because an error has a friendly class name. Instance checks also require care across realms or serialized process boundaries. When wrapping another error, consider preserving it as the cause.
Check the result
Expect true and the required-filename message. Throw an ordinary Error in the same code path and confirm it is not mistaken for a known input problem.
Sources
Reference documentation for the behavior used in this guide: