API Developmentbeginner
Create standardized API error handling
API Error Handler
Create standardized API error handling
Create standardized API error handling.
Instructions
- Define error classes:
class AppError extends Error {
constructor(
public statusCode: number,
public code: string,
message: string,
public details?: unknown
) {
super(message);
}
}
class ValidationError extends AppError {
constructor(details: unknown) {
super(400, 'VALIDATION_ERROR', 'Invalid request data', details);
}
}
class NotFoundError extends AppError {
constructor(resource: string) {
super(404, 'NOT_FOUND', `${resource} not found`);
}
}
class UnauthorizedError extends AppError {
constructor() { super(401, 'UNAUTHORIZED', 'Authentication required'); }
}
class ForbiddenError extends AppError {
constructor() { super(403, 'FORBIDDEN', 'Insufficient permissions'); }
}
class ConflictError extends AppError {
constructor(message: string) { super(409, 'CONFLICT', message); }
}
- Error handler middleware:
function handleError(err: unknown): Response {
if (err instanceof AppError) {
return Response.json({
error: { code: err.code, message: err.message, details: err.details }
}, { status: err.statusCode });
}
// Unknown error — log full details, return generic message
console.error('Unhandled error:', err);
return Response.json({
error: { code: 'INTERNAL_ERROR', message: 'Something went wrong' }
}, { status: 500 });
}
Rules
- Never expose stack traces to clients
- Log full error details server-side
- Use consistent error shape:
{ error: { code, message, details? } }