errors
Shared exception classes with HTTP status codes and Shelf error-handling middleware.
Features
- Structured exception hierarchy mapped to HTTP status codes
- Validation errors with per-field error messages
- Rate limit exceptions with retry-after support
- Database exception wrapper
- Shelf middleware for automatic JSON error responses
Installation
dependencies:
errors: ^1.0.0Usage
Throwing Exceptions
import 'package:errors/errors.dart';
// Simple exceptions
throw NotFoundException('User not found');
throw UnauthorizedException('Invalid credentials');
throw ForbiddenException('Access denied');
throw ConflictException('Email already exists');
// Validation errors with field-level details
throw ValidationException(
'Validation failed',
errors: {
'email': ['Must be a valid email address'],
'password': ['Must be at least 8 characters'],
},
);
// Rate limit with retry-after
throw RateLimitException('Too many requests', retryAfter: 60);
// Database errors
throw DatabaseException('Connection failed', underlyingError: e);Shelf Error Middleware
import 'package:errors/errors.dart';
// Catch AppException only
final handler = Pipeline()
.addMiddleware(errorHandler())
.addHandler(myHandler);
// Catch all exceptions
final handler = Pipeline()
.addMiddleware(errorHandlerAll(
onError: (error, request) { /* AppException */ },
onUnhandledError: (error, stackTrace, request) { /* other */ },
))
.addHandler(myHandler);The middleware converts exceptions to JSON responses:
{"error": "User not found", "code": "not_found"}Exception Classes
| Exception | HTTP Status | Code |
|---|---|---|
BadRequestException | 400 | bad_request |
UnauthorizedException | 401 | unauthorized |
ForbiddenException | 403 | forbidden |
NotFoundException | 404 | not_found |
ConflictException | 409 | conflict |
ValidationException | 422 | validation_error |
RateLimitException | 429 | rate_limit_exceeded |
InternalServerException | 500 | internal_error |
ServiceUnavailableException | 503 | service_unavailable |
DatabaseException | 500 | database_error |