0 day streak
javascript / intermediate
Snippet

Specialized Logic with Custom Error Classes

Extending the built-in Error class allows you to create domain-specific errors. By adding custom properties like 'field' or 'code', you can implement more intelligent error handling and API response logic.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = 'ValidationError';
this.field = field;
this.code = 400;
}
}
try {
throw new ValidationError('Invalid email format', 'email');
} catch (err) {
if (err instanceof ValidationError) {
console.error(`Field [${err.field}] error: ${err.message}`);
}
}
nodejs
Breakdown
1
class ValidationError extends Error
Inherits from the base Error class to maintain stack trace functionality.
2
super(message)
Calls the parent constructor to set the standard error message.
3
err instanceof ValidationError
Accurately identifies the specific error type for targeted handling.