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.0

Usage

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

ExceptionHTTP StatusCode
BadRequestException400bad_request
UnauthorizedException401unauthorized
ForbiddenException403forbidden
NotFoundException404not_found
ConflictException409conflict
ValidationException422validation_error
RateLimitException429rate_limit_exceeded
InternalServerException500internal_error
ServiceUnavailableException503service_unavailable
DatabaseException500database_error