Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Errors Laravel Package

axy/errors

axy/errors is a PHP 8.1+ helper for defining and organizing exception classes. Provides common exception structures, basic error classes, default messages, backtrace truncation, and global options to standardize error handling across projects.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Domain-Specific Exception Hierarchy: The package enforces a structured exception hierarchy (ErrorLogic/Runtime), which aligns well with Laravel’s existing exception handling (e.g., Illuminate\Contracts\Container\BindingResolutionException). This allows for granular error categorization and consistent error propagation.
  • Laravel Compatibility: The package’s design (e.g., NotFound, InvalidValue, ReadOnly) mirrors Laravel’s built-in exceptions (e.g., ModelNotFoundException, ValidationException), reducing cognitive overhead for developers.
  • Backtrace Truncation: The axy/backtrace integration for truncating stack traces is valuable in Laravel for hiding framework internals (e.g., service container, middleware) from end users, improving error messages in production.

Integration Feasibility

  • Low Friction: The package is a drop-in replacement for native PHP exceptions, requiring minimal changes to existing Laravel codebases. Existing try-catch blocks can leverage the new exceptions without breaking changes.
  • PSR-11/PSR-15 Alignment: The package’s design (e.g., Error interface) is compatible with Laravel’s dependency injection and middleware stacks, enabling seamless integration with frameworks like Laravel\Pipeline.
  • Validation Use Case: The InvalidFormat, NotValid, and TypingError exceptions align perfectly with Laravel’s validation layer, offering more expressive error handling for form requests or API payloads.

Technical Risk

  • Backward Compatibility: Introducing custom exceptions may require updating existing catch blocks to handle the new hierarchy (e.g., axy\errors\Logic vs. Runtime). A migration path (see Integration Approach) can mitigate this.
  • Performance Overhead: Backtrace truncation adds minimal overhead (~1–5ms per exception), but this is negligible in Laravel’s request lifecycle.
  • Namespace Pollution: The package encourages a nested namespace structure (e.g., App\Errors\InvalidConfig), which could conflict with existing Laravel conventions if not scoped properly (e.g., App\Exceptions).
  • Testing Impact: Unit tests catching exceptions may need updates to account for the new hierarchy or truncated traces.

Key Questions

  1. Exception Scoping: Should exceptions be namespaced under App\Errors or App\Exceptions to avoid conflicts with Laravel’s built-in exceptions?
  2. Global vs. Local Adoption: Will the package be used globally (e.g., all exceptions) or selectively (e.g., only in specific services)?
  3. Backtrace Truncation Scope: Should truncation apply to all exceptions or only those in certain namespaces (e.g., App\Services)?
  4. Validation Integration: How will these exceptions interact with Laravel’s FormRequest validation layer (e.g., custom error bags)?
  5. Error Logging: Will the truncated traces in logs (e.g., Monolog) impact debugging? If so, should getTrace() be preserved for admins?
  6. API Responses: How will these exceptions be serialized for API responses (e.g., JSON:API, REST)? Will they extend Symfony\Component\HttpKernel\Exception\HttpException?

Integration Approach

Stack Fit

  • Laravel Core: The package integrates seamlessly with Laravel’s exception handling (e.g., App\Exceptions\Handler), allowing customization of HTTP responses, logging, and rendering.
  • Validation: Exceptions like InvalidFormat and NotValid can replace or extend Laravel’s ValidationException, providing more context for API clients.
  • Middleware: Exceptions can be caught in middleware (e.g., App\Http\Middleware\ValidateExceptions) to standardize error responses.
  • Service Container: The Disabled and AdapterNotDefined exceptions are ideal for service container errors (e.g., binding resolution failures).

Migration Path

  1. Phase 1: Adopt Selectively
    • Start by using the package in new services or modules (e.g., App\Services\Payment\InvalidConfig).
    • Replace native exceptions in critical paths (e.g., validation, API responses) first.
  2. Phase 2: Refactor Existing Exceptions
    • Update custom exceptions to extend axy\errors\Logic/Runtime (e.g., App\Exceptions\InvalidUserInput extends axy\errors\InvalidValue).
    • Use trait-based inheritance to avoid breaking changes:
      class MyException extends \RuntimeException implements axy\errors\Error {
          use axy\errors\Traits\TruncatedTrace;
      }
      
  3. Phase 3: Global Replacement
    • Replace Laravel’s built-in exceptions in App\Exceptions\Handler with the new hierarchy (e.g., catch axy\errors\Error as the base case).
    • Update catch blocks in tests and business logic incrementally.

Compatibility

  • PHP 8.1+: The package requires PHP 8.1, which aligns with Laravel’s current LTS support (Laravel 10+).
  • Laravel Services: Works with Laravel’s service container, event system, and middleware without conflicts.
  • Third-Party Packages: No known conflicts with popular Laravel packages (e.g., spatie/laravel-permission, laravel/breeze), as the package focuses on exceptions.

Sequencing

  1. Add Dependency:
    composer require axy/errors
    
  2. Configure Backtrace Truncation: Extend the base exception class to enable truncation globally:
    namespace App\Exceptions;
    
    use axy\errors\Logic;
    use axy\errors\Traits\TruncatedTrace;
    
    class AppException extends Logic {
        use TruncatedTrace;
    }
    
  3. Update Exception Handler: Modify App\Exceptions\Handler to render new exceptions:
    public function render($request, Throwable $exception) {
        if ($exception instanceof axy\errors\Error) {
            return response()->json([
                'error' => $exception->getMessage(),
                'code' => $exception->getCode(),
                'type' => get_class($exception),
            ], $exception->getCode());
        }
        return parent::render($request, $exception);
    }
    
  4. Replace Native Exceptions: Gradually replace instances of RuntimeException, InvalidArgumentException, etc., with the new hierarchy (e.g., InvalidFormat instead of InvalidArgumentException for validation errors).

Operational Impact

Maintenance

  • Reduced Boilerplate: The package’s predefined exceptions reduce the need to create custom exception classes for common scenarios (e.g., NotFound, InvalidValue).
  • Consistent Error Messages: Standardized message formats (e.g., InvalidFormat includes $value and $type) improve debugging and API documentation.
  • Backtrace Management: Truncated traces simplify error reporting for end users while preserving technical details for developers via getTruncatedTrace().

Support

  • Developer Onboarding: The clear hierarchy (Logic vs. Runtime) and documentation (e.g., org.md) reduce onboarding time for new team members.
  • Error Localization: Exceptions include context (e.g., $container, $service), making it easier to diagnose issues in distributed systems (e.g., microservices).
  • API Contracts: Exceptions like Disabled and ActionNotAllowed help define clear API contracts for consumers (e.g., "This endpoint is disabled in this environment").

Scaling

  • Performance: Minimal overhead from backtrace truncation (~1–5ms per exception), which is negligible at scale.
  • Horizontal Scaling: The package’s stateless design (no shared state or caching) ensures it scales with Laravel’s horizontal scaling (e.g., queue workers, API servers).
  • Error Aggregation: Truncated traces work well with error aggregation tools (e.g., Sentry, Bugsnag) by hiding framework noise while preserving actionable details.

Failure Modes

  • Trace Truncation Edge Cases:
    • Risk: Truncated traces may hide critical context if the truncation logic is misconfigured (e.g., wrong namespace).
    • Mitigation: Test truncation with complex call stacks (e.g., middleware → controller → service → exception) and adjust $howTruncateTrace as needed.
  • Exception Hierarchy Confusion:
    • Risk: Developers may accidentally catch axy\errors\Error instead of more specific exceptions (e.g., InvalidConfig), leading to broad error handling.
    • Mitigation: Enforce a coding standard (e.g., "Catch the most specific exception possible") and use IDE hints (e.g., PHPStorm’s "Implement methods" for interfaces like Error).
  • Backward Compatibility Breaks:
    • Risk: Updating catch blocks to handle the new hierarchy may miss some edge cases in legacy code.
    • Mitigation: Use a migration tool (e.g., PHPStan) to detect uncaught exceptions and update them incrementally.

Ramp-Up

  • Training:
    • Workshop: Conduct a 1-hour session on the new exception hierarchy, backtrace truncation, and common use cases (e.g., validation, service container).
    • Cheat Sheet: Provide a reference for
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle