skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    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 = [];
    
    

  2. 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 IlluminateHttpResponse $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 AppHttp;
    
    use IlluminateFoundationHttpKernel as HttpKernel;
    
    class Kernel extends HttpKernel
    {
        protected $middleware = [
            AppHttpMiddlewareSentryStatusCodeMiddleware::class,
            // ...
        ];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search