1.symfony有各种事件和钩子可以用来触发应用程序中的自定义行为。这些事件是由httpkernel组件抛出,可以在kernelevents类中实视。
2.要监听一个事件并添加您自己的自定义逻辑,您必须创建一个服务,该服务将作为该事件的事件侦听器。在这个事件监听器中,您将创建一个服务,将作为一个异常侦听器,允许您修改应用程序所显示的异常。kernelevents::例外事件只是其中的一个核心事件:
1.第一步:
namespace AppBundle\EventListener; use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; class AcmeExceptionListener { public function onKernelException(GetResponseForExceptionEvent $event) { // You get the exception object from the received event $exception = $event->getException(); $message = sprintf( 'My Error says: %s with code: %s', $exception->getMessage(), $exception->getCode() ); // Customize your response object to display the exception details $response = new Response(); $response->setContent($message); // HttpExceptionInterface is a special type of exception that // holds status code and header details if ($exception instanceof HttpExceptionInterface) { $response->setStatusCode($exception->getStatusCode()); $response->headers->replace($exception->getHeaders()); } else { $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR); } // Send the modified response object to the event $event->setResponse($response); } }
2、第二步:注入事件
# app/config/services.yml services: kernel.listener.your_listener_name: class: AppBundle\EventListener\AcmeExceptionListener tags: - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }kernel.exception 指监听整个框架所有的错误
kernel.request 指监听整个框架所有的请求前的事情
method: onKernelException 指监听某个类下的一个方法