在 Symfony 5 中处理异常时未定义的 getException 方法

Undefined getException method while handling exception in Symfony 5

我创建了一个异常 class 如下:

<?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);
    }
}

我已将以下内容添加到我的 services.yaml 文件中:

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

但我收到错误消息:

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

在 Symfony 4.4 中,getException 方法已被弃用,并在 Symfony 5 中被删除。

改用getThrowable。请阅读 documentation.