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

Util Errorhandler Laravel Package

phrity/util-errorhandler

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require phrity/util-errorhandler
    
  2. Basic Usage:

    use Phrity\Util\ErrorHandler;
    
    $handler = new ErrorHandler();
    $result = $handler->with(function () {
        // Your code here
        return "Success";
    });
    
  3. First Use Case: Wrap a risky operation (e.g., third-party API call) to catch errors and convert them to exceptions:

    try {
        $result = $handler->with(function () {
            $response = Http::get('https://api.example.com/unsafe-endpoint');
            return $response->json();
        });
    } catch (ErrorException $e) {
        // Handle the error (e.g., log, retry, or return a fallback)
        Log::error("API call failed: " . $e->getMessage());
        return response()->json(['error' => 'Service unavailable'], 503);
    }
    

Implementation Patterns

Usage Patterns

  1. API Endpoints: Use with() to convert PHP errors into HTTP responses:

    public function riskyOperation(Request $request)
    {
        $handler = new ErrorHandler();
        $result = $handler->with(function () use ($request) {
            // Risky logic (e.g., parsing user input)
            return $this->processInput($request->input());
        }, function (ErrorException $error) {
            // Convert to HTTP response
            return response()->json([
                'error' => $error->getMessage(),
                'code' => $error->getCode()
            ], 422);
        });
        return response()->json($result);
    }
    
  2. Background Jobs: Use withAll() to collect all errors in a batch job:

    public function handle()
    {
        $handler = new ErrorHandler();
        $results = $handler->withAll(function () {
            // Process multiple items
            return array_map(function ($item) {
                return $this->processItem($item);
            }, $this->items);
        }, function (array $errors, $successResult) {
            // Log all errors and return partial results
            Log::error('Batch job errors:', $errors);
            return $successResult; // Return what succeeded
        });
        $this->dispatchAfterCompletion(new LogResultsJob($results));
    }
    
  3. Global Error Handling: Temporarily override Laravel’s error handler for CLI commands:

    $handler = new ErrorHandler();
    $handler->set(function (ErrorException $error) {
        // Custom CLI error handling
        fwrite(STDERR, "Error: " . $error->getMessage() . "\n");
        exit(1);
    });
    // CLI logic here
    $handler->restore(); // Restore Laravel's default handler
    
  4. Filtering Errors: Ignore E_NOTICE but throw on E_USER_ERROR:

    $result = $handler->with(function () {
        // Code that might trigger notices or errors
    }, null, E_USER_ERROR);
    

Workflows

  1. Error-to-Exception Conversion: Replace @ suppression with structured error handling:

    // Before (risky)
    $data = @json_decode($response->body());
    
    // After (structured)
    $data = $handler->with(function () use ($response) {
        return json_decode($response->body());
    });
    
  2. Custom Exception Wrapping: Convert errors into domain-specific exceptions:

    $result = $handler->with(function () {
        // Risky logic
    }, new PaymentGatewayException('Failed to process payment'));
    
  3. Fallback Logic: Use callbacks to implement retries or defaults:

    $result = $handler->with(function () {
        return $this->fetchFromPrimarySource();
    }, function (ErrorException $error) {
        return $this->fetchFromBackupSource();
    });
    

Integration Tips

  1. Laravel Service Container: Bind the handler for dependency injection:

    $this->app->singleton(ErrorHandler::class, function ($app) {
        return new ErrorHandler();
    });
    

    Then inject it into controllers/jobs:

    public function __construct(private ErrorHandler $handler) {}
    
  2. Middleware: Wrap API routes to handle errors globally:

    public function handle($request, Closure $next)
    {
        $handler = new ErrorHandler();
        return $handler->with(function () use ($request, $next) {
            return $next($request);
        }, function (ErrorException $error) {
            return response()->json([
                'error' => 'Server error',
                'message' => env('APP_DEBUG') ? $error->getMessage() : null
            ], 500);
        });
    }
    
  3. Testing: Simulate errors in tests:

    public function test_error_handling()
    {
        $handler = new ErrorHandler();
        $this->expectException(ErrorException::class);
        $handler->with(function () {
            trigger_error("Test error", E_USER_ERROR);
        });
    }
    

Gotchas and Tips

Pitfalls

  1. Global Handler Conflicts:

    • Overriding the global handler with set() can interfere with Laravel’s debug bar, logging, or exception handling.
    • Fix: Always call restore() after use, or limit set() to CLI/command contexts.
  2. Error Level Mismatches:

    • Laravel’s App\Exceptions\Handler may not process ErrorExceptions thrown by this package if they’re not rethrown.
    • Fix: Ensure exceptions bubble up to Laravel’s handler by not catching them unless necessary:
      // Avoid swallowing exceptions unless intentional
      try {
          $handler->with(...);
      } catch (ErrorException $e) {
          // Only catch if you need custom logic
          throw $e; // Re-throw to let Laravel handle it
      }
      
  3. Performance in Loops:

    • Wrapping every iteration of a loop in with() adds overhead.
    • Fix: Use withAll() for batch operations or limit usage to critical sections.
  4. Callback Return Values:

    • The with() method returns the result of the callback or the error callback. If both return values, the error callback’s result takes precedence.
    • Fix: Design callbacks to return consistent types (e.g., always return null or a default value in error cases).
  5. Error Context Loss:

    • ErrorExceptions may lose context (e.g., file/line) if not thrown immediately.
    • Fix: Prefer with() over withAll() when you need precise error locations.

Debugging

  1. Silent Failures:

    • If errors aren’t being caught, verify:
      • The error level matches (e.g., E_ALL vs. E_USER_ERROR).
      • The global handler isn’t interfering (check with restore()).
      • PHP’s error_reporting isn’t suppressing errors.
  2. Unexpected Exceptions:

    • If a RuntimeException is thrown instead of an ErrorException, check the second parameter of with()/withAll():
      // This will throw a RuntimeException, not ErrorException
      $handler->with(fn() => trigger_error("Test"), new RuntimeException());
      
  3. Logging:

    • Add debug logs to callbacks to trace execution:
      $handler->with(function () {
          Log::debug("Executing risky block");
          // ...
      }, function (ErrorException $error) {
          Log::error("Error caught", ['error' => $error]);
      });
      

Tips

  1. Combine with Laravel Features:

    • Use report() in error callbacks to leverage Laravel’s exception reporting:
      $handler->with(function () { /* ... */ }, function (ErrorException $error) {
          report($error); // Logs to Laravel's channels
          return response()->json(['error' => 'Internal server error'], 500);
      });
      
  2. Custom Error Levels:

    • Define reusable error level constants:
      const CRITICAL_ERRORS = E_USER_ERROR | E_USER_WARNING;
      $handler->with(fn() => ..., null, CRITICAL_ERRORS);
      
  3. Immutable Handler:

    • Instantiate the handler once (e.g., in a service container) to avoid recreating it:
      $handler = app(ErrorHandler::class);
      
  4. Testing Edge Cases:

    • Test with different error levels and combinations:
      public function test_error_levels()
      {
          $handler = new ErrorHandler();
          $this->expectException(ErrorException::class);
          $handler->with(function () {
              trigger_error("Warning", E_USER_WARNING);
          }, null, E_USER_WARNING);
      }
      
  5. Extension Points:

    • Create decorators to add Laravel-specific logic:
      class LaravelErrorHandlerDecorator
      {
          public function __construct(private Error
      
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity