javascript / beginner
Snippet
Creating Custom Error Classes with ES6 Class Inheritance
Object-oriented inheritance allows creating custom Error classes with specialized metadata (such as HTTP status codes) for structured error handling in application APIs.
snippet.js
javascript
1
2
3
4
5
6
7
8
// lib/errors.jsexport class APIValidationError extends Error {constructor(message, statusCode = 400) {super(message);this.name = 'APIValidationError';this.statusCode = statusCode;}}
nextjs
Breakdown
1
export class APIValidationError extends Error {
Defines a custom class that inherits standard JavaScript Error behavior.
2
constructor(message, statusCode = 400) {
Initializes new error instances with a message and an HTTP status code parameter.
3
super(message);
Calls the parent Error class constructor to properly attach the error message.
4
this.name = 'APIValidationError';
Sets a specific class name property for identifying the custom error type.
5
this.statusCode = statusCode;
Attaches a custom HTTP status code property to the error object.