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

Exceptions Laravel Package

errors/exceptions

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require errors/exceptions
    
    • Automatically registers an exception-based error handler via set_error_handler().
    • No manual configuration required for basic usage.
  2. First Use Case:

    • Native PHP errors (e.g., E_ERROR, E_WARNING) now throw exceptions instead of triggering error callbacks.
    • Example:
      // This will throw an \ErrorException instead of calling error_handler()
      trigger_error("Test error", E_USER_ERROR);
      
  3. Where to Look First:


Implementation Patterns

Core Workflows

  1. Exception-Based Error Handling:

    • Replace set_error_handler() with this package for consistent exception handling.
    • Example:
      try {
          $result = riskyOperation();
      } catch (\ErrorException $e) {
          // Handle errors as exceptions (e.g., log, notify, or rethrow)
          Log::error("Error occurred", ['exception' => $e]);
      }
      
  2. Integration with Laravel:

    • Global Exception Handling: Use Laravel’s App\Exceptions\Handler to catch \ErrorException alongside other exceptions.
      public function render($request, Throwable $exception)
      {
          if ($exception instanceof \ErrorException) {
              return response()->json([
                  'error' => $exception->getMessage(),
                  'code' => $exception->getCode(),
              ], $exception->getCode());
          }
          // ... other exception handling
      }
      
    • Middleware for Error Conversion: Create middleware to ensure all errors are converted to exceptions (e.g., for APIs):
      public function handle($request, Closure $next)
      {
          set_error_handler(function ($severity, $message, $file, $line) {
              throw new \ErrorException($message, $severity, $file, $line);
          });
          return $next($request);
      }
      
  3. Deprecation Handling:

    • Enable deprecation exceptions in .env:
      PHP_ERROR_EXCEPTION_DEPRECATIONS=1
      
    • Catch deprecations in render():
      if ($exception instanceof \ErrorException && $exception->getSeverity() === E_DEPRECATED) {
          // Log or notify about deprecations
      }
      
  4. Testing:

    • Bypass the handler in tests:
      PHP_ERROR_EXCEPTIONS=0
      
    • Mock exceptions in unit tests:
      $this->expectException(\ErrorException::class);
      trigger_error("Test error", E_USER_ERROR);
      

Gotchas and Tips

Pitfalls

  1. Archived Package:

  2. Environment Variable Quirks:

    • PHP_ERROR_EXCEPTIONS=0 must be set to 0 (not false, "", or null). Other values are ignored.
    • Deprecation handling (PHP_ERROR_EXCEPTION_DEPRECATIONS) only works for E_DEPRECATED and E_USER_DEPRECATED.
  3. BC Breaks:

    • Older code relying on DISABLE_PHP_ERROR_EXCEPTIONS will fail. Update to PHP_ERROR_EXCEPTIONS=0.
  4. Performance:

    • Exception throwing is slower than native error handling. Avoid in high-performance contexts (e.g., CLI scripts).
  5. Error Context Loss:

    • Native error context (e.g., $_SERVER, $_GET) is not preserved in \ErrorException. Use debug_backtrace() if needed:
      $exception = new \ErrorException($message, $severity, $file, $line, $context);
      

Debugging Tips

  1. Verify Handler Registration:

    • Check if the handler is active:
      var_dump(set_error_handler('var_dump') !== false); // Should return true
      
    • If not, ensure no other handler (e.g., from whoops) is overriding it.
  2. Log Unhandled Exceptions:

    • Laravel’s App\Exceptions\Handler should log uncaught \ErrorException:
      public function report(Throwable $exception)
      {
          if ($exception instanceof \ErrorException) {
              Log::critical('Unhandled error', [
                  'message' => $exception->getMessage(),
                  'file' => $exception->getFile(),
                  'line' => $exception->getLine(),
              ]);
          }
      }
      
  3. Custom Exception Classes:

    • Extend \ErrorException for domain-specific errors:
      class ValidationErrorException extends \ErrorException {}
      
    • Update the handler to throw custom exceptions:
      set_error_handler(function ($severity, $message) {
          if (strpos($message, 'validation') !== false) {
              throw new ValidationErrorException($message, $severity);
          }
          throw new \ErrorException($message, $severity);
      });
      

Extension Points

  1. Custom Error Handler:

    • Replace the default handler by providing a compatible package (via composer.json):
      {
          "provide": {
              "errors/exceptions": "your-package/v1.0.0"
          }
      }
      
    • Your package must implement the specification.
  2. Error Severity Mapping:

    • Map PHP error levels to custom exception types:
      $severityMap = [
          E_ERROR => \RuntimeException::class,
          E_WARNING => \WarningException::class,
      ];
      set_error_handler(function ($severity, $message) use ($severityMap) {
          $class = $severityMap[$severity] ?? \ErrorException::class;
          throw new $class($message, $severity);
      });
      
  3. Integration with Monolog:

    • Use Monolog’s ErrorHandler to log exceptions:
      $log = new Monolog\Logger('name');
      $handler = new Monolog\Handler\StreamHandler('php://stderr');
      $log->pushHandler($handler);
      set_exception_handler(function ($e) use ($log) {
          $log->error('Exception', ['exception' => $e]);
      });
      
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
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