JavaScript: Error
An Error object describes a failure with a name, message, and often a stack that helps developers diagnose it.
What you will learn
- How to create and inspect an Error
- How to throw an error for a caller to handle
- How to separate safe user messages from diagnostic details
Minimal example
function requireId(value) {
if (!value) {
throw new Error('An id is required');
}
return value;
}
try {
requireId('');
} catch (error) {
console.error(error.name, error.message);
}Throw an Error when a function cannot fulfill its contract. Catch it at a layer that can recover or report the failure meaningfully.
Common mistakes
- Do not throw plain strings; Error objects preserve useful diagnostic information.
- Do not display stack traces, database details, or secrets to users.
- Keep the original error as a cause when wrapping it so debugging context is not lost.