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

Phpbrake Laravel Package

airbrake/phpbrake

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require airbrake/phpbrake
    

    Add the service provider and alias to config/app.php:

    'providers' => [
        // ...
        Airbrake\PHPBrake\ServiceProvider::class,
    ],
    'aliases' => [
        // ...
        'Airbrake' => Airbrake\PHPBrake\Facades\Airbrake::class,
    ],
    
  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="Airbrake\PHPBrake\ServiceProvider" --tag="config"
    

    Update .env with your project ID and API key:

    AIRBRAKE_PROJECT_ID=your_project_id
    AIRBRAKE_API_KEY=your_api_key
    
  3. First Error Capture Trigger an error to test:

    Airbrake::notify('Test error', new \Exception('This is a test error'));
    

    Verify the error appears in your Airbrake dashboard.


Where to Look First

  • Config File: config/airbrake.php – Adjust environment, filters, and integrations.
  • Facade: Airbrake::notify() – Primary method for error reporting.
  • Middleware: Airbrake\PHPBrake\Middleware\ReportExceptions – Auto-capture exceptions in Laravel.

Implementation Patterns

1. Auto-Capturing Exceptions (Laravel Integration)

Add the middleware to app/Http/Kernel.php:

protected $middleware = [
    // ...
    \Airbrake\PHPBrake\Middleware\ReportExceptions::class,
];
  • Pros: No manual try-catch blocks; all uncaught exceptions are reported.
  • Cons: May report expected errors (e.g., 404s). Use config/airbrake.php to filter them:
    'ignore_status_codes' => [404, 403],
    

2. Manual Error Reporting

Useful for logging business logic errors or silent failures:

try {
    $user = User::findOrFail($id);
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
    Airbrake::notify('User not found', $e, [
        'user_id' => $id,
        'context' => 'API endpoint',
    ]);
}
  • Key Parameters:
    • Message: Human-readable error description.
    • Exception: The thrown exception.
    • Context: Associative array of additional data (e.g., request IDs, user IDs).

3. Custom Error Handling with ErrorHandler

Extend the default handler for pre-processing:

Airbrake::setErrorHandler(function (Throwable $exception, array $context = []) {
    // Add custom logic (e.g., redact sensitive data)
    $context['sanitized'] = true;
    return Airbrake::notify('Custom handler', $exception, $context);
});

4. Framework-Specific Integrations

  • Laravel: Use Airbrake::boot() in AppServiceProvider to auto-configure.
  • Symfony: Integrate with ErrorListener or HttpKernel.
  • PSR-3 Loggers: Forward logs to Airbrake via a custom handler:
    $logger = new AirbrakeLogger(Airbrake::getClient());
    $monolog->pushHandler($logger);
    

5. Environment-Specific Config

Use Laravel’s .env to toggle Airbrake per environment:

AIRBRAKE_ENABLED=true          # Global toggle
AIRBRAKE_ENABLED_PRODUCTION=true # Override for production

In config/airbrake.php:

'enabled' => env('AIRBRAKE_ENABLED', false),

Gotchas and Tips

Pitfalls

  1. Performance Overhead

    • Disable in non-production environments (AIRBRAKE_ENABLED=false).
    • Avoid reporting in bulk operations (e.g., batch jobs). Use sampling:
      if (rand(0, 100) < 10) { // 10% chance
          Airbrake::notify('Batch job error', $e);
      }
      
  2. Sensitive Data Leakage

    • Never include raw request payloads or tokens in context. Use:
      'user_id' => $user->id, // Safe
      'api_key' => 'REDACTED', // Explicitly redact
      
    • Configure config/airbrake.php to filter sensitive keys:
      'filter_keys' => ['password', 'api_key', 'token'],
      
  3. Duplicate Errors

    • Airbrake groups similar errors. Use unique error messages:
      Airbrake::notify("Failed to process order #{$order->id}", $e);
      
  4. Middleware Conflicts

    • If using ReportExceptions, ensure it runs after Laravel’s App\Exceptions\Handler to avoid double-processing.

Debugging Tips

  1. Verify API Key/Project ID

    • Test with a dummy error to confirm the config is correct:
      Airbrake::notify('Test', new \Exception('Debug: Is this reaching Airbrake?'));
      
  2. Check HTTP Status Codes

    • Airbrake ignores errors with ignore_status_codes (e.g., 404). Adjust in config/airbrake.php if needed.
  3. Log Locally First

    • Use Log::error() alongside Airbrake::notify() during development:
      Log::error('Local log', ['exception' => $e]);
      Airbrake::notify('Remote log', $e);
      
  4. Inspect the Client

    • Access the underlying client for advanced use:
      $client = Airbrake::getClient();
      $client->setEnvironment('staging'); // Override environment
      

Extension Points

  1. Custom Notifiers

    • Implement Airbrake\PHPBrake\NotifierInterface for non-HTTP errors (e.g., CLI jobs):
      Airbrake::setNotifier(new CustomNotifier());
      
  2. Webhook Integration

    • Use Airbrake’s API to forward errors to Slack/Teams:
      $webhookUrl = 'https://hooks.slack.com/...';
      $payload = Airbrake::getClient()->getLastError();
      Http::post($webhookUrl, $payload);
      
  3. Error Grouping

    • Use error_id to group related errors (e.g., failed payments):
      Airbrake::notify('Payment failed', $e, [
          'error_id' => 'payment_' . $payment->id,
      ]);
      
  4. Rate Limiting

    • Throttle notifications to avoid API rate limits:
      if (!Airbrake::isRateLimited()) {
          Airbrake::notify('Rate-limited error', $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.
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
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