namespace App\EventListener;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
class CustomExceptionListener
{
public function onKernelException(ExceptionEvent $event)
{
$exception = $event->getThrowable();
if ($exception instanceof MethodNotAllowedHttpException) {
$response = new JsonResponse('custom error ');
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
}else{
return;
}
$event->setResponse($response);
}
}
您需要创建一个事件监听器并监听
kernel.exception
然后注册这个监听器
service.yaml
这是文档的另一个链接。
会有问题 - 问。