Custom exception classes extend **Error** to add context-specific properties (HTTP status codes, validation field names, error codes). They integrate with try/catch and support **instanceof** checks, allowing catch blocks to handle different error types precisely. Always set `this.name` in the constructor.
1Understanding Custom Exceptions
Custom exception classes extend Error to add context-specific properties (HTTP status codes, validation field names, error codes). They integrate with try/catch and support instanceof checks, allowing catch blocks to handle different error types precisely. Always set this.name in the constructor.
Create an error hierarchy: AppError → NetworkError, ValidationError, AuthError. Catch at the right level.
class NetworkError extends Error {
constructor(url, status) {
super(`Failed to fetch ${url}: HTTP ${status}`);
this.name = 'NetworkError';
this.url = url;
this.status = status;
}
}
try {
throw new NetworkError('/api/users', 503);
} catch (e) {
if (e instanceof NetworkError) {
console.log(e.name, e.status, e.url);
}
}2Practical Example
Here is a real-world application of Custom Exceptions showing how it is used in production JavaScript code.
class ValidationError extends Error {
constructor(errors) {
super('Validation failed');
this.name = 'ValidationError';
this.errors = errors; // { field: message }
}
}
function validate(data) {
const errors = {};
if (!data.email?.includes('@')) errors.email = 'Invalid email';
if (!data.name) errors.name = 'Name is required';
if (Object.keys(errors).length) throw new ValidationError(errors);
}
try { validate({ email: 'bad', name: '' }); }
catch (e) { console.log(e.errors); }3Best Practices
Follow these guidelines when working with Custom Exceptions:
1. Always call super(message) first
2. Set this.name to the class name
3. Add relevant context properties (code, field, statusCode)
Tip: Create an error hierarchy: AppError → NetworkError, ValidationError, AuthError. Catch at the right level.
class NetworkError extends Error {
constructor(url, status) {
super(`Failed to fetch ${url}: HTTP ${status}`);
this.name = 'NetworkError';
this.url = url;
this.status = status;
}
}
try {
throw new NetworkError('/api/users', 503);
} catch (e) {
if (e instanceof NetworkError) {
console.log(e.name, e.status, e.url);
}
}