Custom Errors in JavaScript
Create custom errors in JavaScript with classes that extend Error, extra fields like code, an error factory and toJSON for logging. Explanation and output.
1// Method 1: Custom error class2class CustomError extends Error {3 constructor(message, code) {4 super(message);5 this.name = 'CustomError';6 this.code = code;7 }8}910try {11 throw new CustomError('Something went wrong', 'ERR001');12} catch (error) {13 console.error('Custom error:', error.message);14 console.error('Error code:', error.code);15}1617// Method 2: Multiple custom errors18class ValidationError extends Error {19 constructor(message, field) {20 super(message);21 this.name = 'ValidationError';22 this.field = field;23 }24}2526class NotFoundError extends Error {27 constructor(resource) {28 super(`${resource} not found`);29 this.name = 'NotFoundError';30 this.resource = resource;31 }32}3334try {35 throw new ValidationError('Invalid email', 'email');36} catch (error) {37 if (error instanceof ValidationError) {38 console.error('Validation error:', error.message, 'Field:', error.field);39 }40}4142// Method 3: Error factory43function createError(type, message, details = {}) {44 const error = new Error(message);45 error.name = type;46 Object.assign(error, details);47 return error;48}4950try {51 throw createError('DatabaseError', 'Connection failed', { host: 'localhost', port: 5432 });52} catch (error) {53 console.error('Error:', error.name, error.message, error.host);54}5556// Method 4: Error with stack trace57class DetailedError extends Error {58 constructor(message, context = {}) {59 super(message);60 this.name = 'DetailedError';61 this.context = context;62 this.timestamp = new Date().toISOString();63 }6465 toJSON() {66 return {67 name: this.name,68 message: this.message,69 context: this.context,70 timestamp: this.timestamp,71 stack: this.stack72 };73 }74}7576const error = new DetailedError('Operation failed', { userId: 123, action: 'update' });77console.log('Error JSON:', JSON.stringify(error, null, 2));
Sample Output
"timestamp": "2024-01-15T10:30:45.123Z"
This is the time the error was created. Your run shows your own current time.
"stack": "DetailedError: Operation failed\n at ..."
The real stack lists file names and line numbers. The \n marks are line breaks inside the string.
In this one
- How to build an error class with extends and super
- How to add fields like code and field to an error
- How to tell error types apart with instanceof
- Why toJSON helps when you log errors
How it works
- 1
CustomError is thrown, and catch prints its message and code.
- 2
ValidationError is thrown, and instanceof confirms the type.
- 3
createError builds a DatabaseError with a host field.
- 4
DetailedError is created with context and a timestamp.
- 5
JSON.stringify calls toJSON and prints the full record.
Edge cases
Forgetting super(message)
Using this before super throws a ReferenceError.
Call super(message) as the first line of the constructor.
Name stays "Error"
error.name prints Error, not your class name.
Set this.name in the constructor.
Plain JSON.stringify(error)
A normal Error turns into {}.
Add a toJSON method or copy message and stack yourself.
What's going on
The built-in Error tells you that something failed, but not much more. In a real app you want to know what kind of problem it was. Was it bad input, a missing record or a database issue? Custom errors in JavaScript let you add that detail.
A custom error is a class that extends Error. "Extends" means the new class gets everything Error has and can add more. In the constructor you call super(message) first. super runs the parent Error constructor, which sets the message and the stack. Then you set this.name and any extra fields, like a code.
Method 1 adds a code such as ERR001. Codes are easy for programs to compare, and they stay the same even if the message text changes.
Method 2 makes two classes, ValidationError and NotFoundError. The catch block uses instanceof to check the class, so each type can be handled in its own way. ValidationError also keeps the field name, so a form can mark the wrong input.
Method 3 is an error factory. A factory is a plain function that builds and returns an object. It creates a normal Error, changes its name, and copies extra details onto it with Object.assign.
Method 4 adds a timestamp and a toJSON method. JSON.stringify skips the message and stack of a normal Error, so the result would be almost empty. When an object has toJSON, JSON.stringify uses what it returns. That gives a full record you can save in a log.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What must a custom error constructor call first?
Pick an answer to check it.
Question 2
What does instanceof ValidationError check?
Pick an answer to check it.
Questions people ask
Why use a code if I already have a message?
Code checks are stable. Messages can change or be translated.
Is instanceof safe with custom errors?
Yes, with class syntax it works for each subclass and for Error.
Should every error be a custom class?
No. Make one only when callers need to treat that error differently.