我创建了一个异常类如下:
<?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".
个
1条答案
按热度按时间zu0ti5jz1#
在Symfony 4.4中,
getException
方法被弃用,并在Symfony 5中被删除。使用
getThrowable
。