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

Error Report Bundle Laravel Package

ccetc/error-report-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your Symfony/Laravel project via Composer:

    composer require ccetc/error-report-bundle
    

    For Laravel (Symfony-based), register the bundle in config/bundles.php:

    return [
        // ...
        CCETC\ErrorReportBundle\CCETCErrorReportBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config:

    php artisan vendor:publish --tag=ccetc-error-report-config
    

    Update config/packages/ccetc_error_report.yaml to define:

    • report_endpoint (e.g., a Laravel route or Symfony controller endpoint).
    • allowed_origins (CORS settings for frontend submissions).
    • storage (e.g., database or file for report storage).
  3. First Use Case: Capture a User Report Trigger a report via JavaScript (frontend) or PHP (backend):

    // Frontend (e.g., in a global error handler)
    window.addEventListener('error', (event) => {
        fetch('/report-error', {
            method: 'POST',
            body: JSON.stringify({
                message: event.message,
                stack: event.error?.stack,
                url: window.location.href,
            }),
            headers: { 'Content-Type': 'application/json' }
        });
    });
    

    Or manually in Laravel:

    use CCETC\ErrorReportBundle\Service\ErrorReportService;
    
    $reportService = app(ErrorReportService::class);
    $reportService->createReport([
        'message' => 'Test error',
        'context' => ['user_id' => auth()->id()],
    ]);
    

Implementation Patterns

Workflow: End-to-End Error Reporting

  1. Frontend Integration

    • Use the provided JavaScript snippet to capture window.onerror, Promise.rejection, or custom events.
    • Attach metadata (e.g., user session, browser info) via context:
      fetch('/report-error', {
          body: JSON.stringify({
              message: 'Crash!',
              context: {
                  user_agent: navigator.userAgent,
                  session_id: getCookie('session_id')
              }
          })
      });
      
  2. Backend Processing

    • Define a Laravel route (routes/web.php):
      use CCETC\ErrorReportBundle\Controller\ErrorReportController;
      
      Route::post('/report-error', [ErrorReportController::class, 'store']);
      
    • Extend the ErrorReport entity (if needed) by creating a custom migration or using the bundle’s events:
      // app/Events/ErrorReportCreated.php
      class ErrorReportCreated implements ShouldBroadcast
      {
          public function handle(ErrorReport $report) {
              // Send to Slack, log to Sentry, etc.
          }
      }
      
  3. Storage and Retrieval

    • Query reports via Eloquent:
      $reports = \App\Models\ErrorReport::with('context')
          ->where('created_at', '>', now()->subDays(7))
          ->get();
      
    • For file storage, check storage/logs/error_reports/ (default path).
  4. Automation

    • Use Laravel’s scheduler to process reports:
      // app/Console/Commands/ProcessErrorReports.php
      public function handle() {
          $reports = \App\Models\ErrorReport::pending()->limit(100)->get();
          foreach ($reports as $report) {
              $this->processReport($report);
          }
      }
      

Integration Tips

  • Symfony/Laravel Hybrid: If using Symfony components, inject the bundle’s ErrorReportService directly:
    $this->container->get('ccetc_error_report.service');
    
  • Validation: Override the ErrorReport entity’s validation rules in app/Models/ErrorReport.php:
    protected $rules = [
        'message' => 'required|string|max:2000',
        'context' => 'nullable|array',
    ];
    
  • Localization: Translate error messages via Laravel’s lang files (e.g., resources/lang/en/error_report.php).

Gotchas and Tips

Pitfalls

  1. CORS Issues

    • If the frontend fails to submit reports, verify allowed_origins in config matches your frontend domain.
    • Test with:
      curl -X POST -H "Origin: http://your-frontend.com" -H "Content-Type: application/json" \
           -d '{"message":"test"}' http://your-backend.com/report-error
      
  2. Storage Quirks

    • Database: Ensure the error_reports table exists (run migrations if using custom storage).
    • File Storage: Reports are saved as JSON files. Avoid large files (>1MB) to prevent performance issues. Fix: Add a max_size config or validate payload size in the controller.
  3. Event System

    • The bundle dispatches ErrorReportCreated events, but they may not be subscribed by default.
    • Listen for events in EventServiceProvider:
      protected $listen = [
          \CCETC\ErrorReportBundle\Events\ErrorReportCreated::class => [
              \App\Listeners\LogToSlack::class,
          ],
      ];
      
  4. Rate Limiting

    • No built-in rate limiting exists. Add middleware to prevent abuse:
      Route::post('/report-error', function () {
          if (request()->ip() === old('reported_ip', '')) {
              abort(429, 'Too many reports');
          }
          // ...
      })->middleware('throttle:10,1');
      

Debugging

  • Missing Reports: Check Laravel logs (storage/logs/laravel.log) for failed submissions.
  • Config Overrides: Use php artisan config:clear if changes to ccetc_error_report.yaml aren’t applied.
  • Database Issues: Run php artisan migrate if the error_reports table is missing.

Extension Points

  1. Custom Fields Extend the ErrorReport model to add fields (e.g., screenshot_url):

    // app/Models/ErrorReport.php
    protected $casts = [
        'context' => 'array',
        'screenshot_url' => 'string',
    ];
    

    Update the controller to accept new fields.

  2. Alternative Storage Override the storage engine by binding a custom service:

    // config/services.php
    'ccetc_error_report.storage' => \App\Services\S3ErrorReportStorage::class,
    
  3. API Versioning Use Laravel’s API resources to version the report endpoint:

    Route::post('/v1/report-error', [ErrorReportController::class, 'storeV1']);
    
  4. Testing Mock the ErrorReportService in tests:

    $this->mock(ErrorReportService::class)->shouldReceive('createReport')->once();
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware