Node.js › Error Handling
How would you create and use custom Error subclasses in a Node.js application to represent different categories of application-specific errors?
IntermediateAnswer
Extending the built-in Error class lets you attach additional context (an HTTP status code, an error code, whether the error is operational) and lets calling code distinguish error types via instanceof checks, rather than parsing error message strings, which is fragile and prone to breaking when messages change.
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = 'ValidationError';
this.field = field;
this.statusCode = 400;
this.isOperational = true;
}
}
if (!email.includes('@')) throw new ValidationError('Invalid email format', 'email');Real-world example An API's global error-handling middleware checks 'if (err instanceof ValidationError)' to return a 400 response with the specific invalid field, versus a generic 500 for unrecognized error types, giving API consumers precise, structured error information rather than a generic failure message.