nas
nas

Reputation: 2417

Undefined getException method while handling exception in Symfony 5

I created an exception class as follows:

<?php

declare(strict_types=1);

namespace App\Exception;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use function strpos;

final class HTTPExceptionListener
{
    public function onKernelException(ExceptionEvent $event): void
    {
        $exception = $event->getException();
        if (! ($exception instanceof HttpException) || strpos($event->getRequest()->getRequestUri(), '/api/') === false) {
            return;
        }

        $response = new JsonResponse(['error' => $exception->getMessage()]);
        $response->setStatusCode($exception->getStatusCode());
        $event->setResponse($response);
    }
}

I have added following to my services.yaml file:

 App\Exception\HTTPExceptionListener:
        tags:
            - { name: kernel.event_listener, event: kernel.exception }

But I am getting error:

Attempted to call an undefined method named "getException" of class "Symfony\Component\HttpKernel\Event\ExceptionEvent".

Upvotes: 1

Views: 2697

Answers (1)

Mike Doe
Mike Doe

Reputation: 17576

In Symfony 4.4 the getException method was deprecated, and was removed in Symfony 5.

Use getThrowable instead.


Upvotes: 6

Related Questions