1

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".

4
  • 3
    Shouldn't you call $event->getThrowable() ? Commented Jan 13, 2020 at 7:55
  • 1
    So can't you simply open the ExceptionEvent class and inspect its methods? Commented Jan 13, 2020 at 7:58
  • @emix I am getting error in this line $exception = $event->getException(); Commented Jan 13, 2020 at 8:00
  • 2
    1) open the class 2) notice there's no getException method, the error message is self explanatory 3) look for other methods 4) notice the getThrowable method 5) use getThrowable instead 6) read the docs Commented Jan 13, 2020 at 8:06

1 Answer 1

6

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

Use getThrowable instead.


Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.