Error Handling
Custom error classes for consistent error management.
Error Handling
The error utilities provide custom error classes for different error types and a formatter for consistent error responses.
Error Classes
AppError
Base error class for application errors.
import { AppError } from '@/lib/utils/errors';
throw new AppError('Something went wrong', 'CUSTOM_ERROR', 500);
ValidationError
For input validation failures (400 status).
import { ValidationError } from '@/lib/utils/errors';
throw new ValidationError('Invalid input data', {
email: ['Invalid email format'],
password: ['Too short', 'Must contain number'],
});
NotFoundError
For missing resources (404 status).
import { NotFoundError } from '@/lib/utils/errors';
throw new NotFoundError('User');
// Results in: "User not found"
UnauthorizedError
For authentication failures (401 status).
import { UnauthorizedError } from '@/lib/utils/errors';
throw new UnauthorizedError('Invalid credentials');
ForbiddenError
For authorization failures (403 status).
import { ForbiddenError } from '@/lib/utils/errors';
throw new ForbiddenError('Admin access required');
Error Formatter
Convert any error to a consistent response format:
import { formatError } from '@/lib/utils/errors';
try {
await someOperation();
} catch (error) {
const formatted = formatError(error);
// {
// message: string,
// code: string,
// statusCode: number,
// fields?: Record<string, string[]>
// }
return Response.json(formatted, { status: formatted.statusCode });
}
Error Properties
| Error Type | Code | Status |
|---|---|---|
| ValidationError | VALIDATION_ERROR | 400 |
| UnauthorizedError | UNAUTHORIZED | 401 |
| ForbiddenError | FORBIDDEN | 403 |
| NotFoundError | NOT_FOUND | 404 |
| AppError (default) | custom | 500 |