class ApiError extends Error {
constructor(message, code, status = 500, details = {}) {
super(message);
this.name = this.constructor.name;
this.code = code;
this.status = status;
this.details = details;
}
}
class ValidationError extends ApiError {
constructor(field, value) {
super(`Invalid ${field}: ${value}`, 'VALIDATION_ERROR', 400, { field, value });
}
}
class NotFoundError extends ApiError {
constructor(resource) {
super(`${resource} not found`, 'NOT_FOUND', 404);
}
}
// Usage in API handler
try {
const user = await getUser(id);
} catch (error) {
if (error instanceof ValidationError) {
return Response.json({ error: error.message }, { status: 400 });
}
if (error instanceof NotFoundError) {
return Response.json({ error: error.message }, { status: 404 });
}
throw error;
}