Home > other >  How to send all bad requests to Sentry from Laravel app?
How to send all bad requests to Sentry from Laravel app?

Time:09-28

I added sentry.io integration to a Laravel application

    public function register()
    {
        $this->reportable(function (Throwable $e) {
            if (app()->bound('sentry')) {
                app('sentry')->captureException($e);
            }
        });
    }

If works fine if there are exceptions. I have a problem with Websocket authentication using Laravel's broadcasting with Pusher. From time to time it returns 403 when JTW token is refreshed. I cannot reproduce it locally.

How can I log all 4xx and 5xx requests to Sentry?

CodePudding user response:

I think the best option is to use middleware.

  1. Create a middleware php artisan make:middleware SentryStatusCodeMiddleware
  2. Edit app/Http/Middleware/SentryStatusCodeMiddleware.php
public function handle(Request $request, Closure $next)
{
    /** @var \Illuminate\Http\Response $response */
    $response = $next($request);

    $statusCode = $response->getStatusCode();

    if (400 <= $statusCode && $statusCode < 600) {
        if (app()->bound('sentry')) {
            $exception = new \Exception('New ' . $statusCode . ' Exception!');

            app('sentry')->captureException($exception);
        }
    }

    return $response;
}
  1. Add middleware to app/Http/Kernel.php file
<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    protected $middleware = [
        \App\Http\Middleware\SentryStatusCodeMiddleware::class,
        // ...
    ];

CodePudding user response:

By default Laravel doesn't report there exceptions

    protected $internalDontReport = [
        AuthenticationException::class,
        AuthorizationException::class,
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        MultipleRecordsFoundException::class,
        RecordsNotFoundException::class,
        SuspiciousOperationException::class,
        TokenMismatchException::class,
        ValidationException::class,
    ];

you need an override in Hander.php

protected $internalDontReport = [];

  • Related