问题描述
发生404错误时,我需要能够记录/接收电子邮件.我可以在文档中看到如何为这些错误设置新模板,但是如何首先在控制器中捕获它们,以便实现日志记录/发出消息的逻辑?
I need to be able to log/receive an email when a 404 error occurs. I can see in the docs how to set up a new template for these errors, but how do I catch them in the first place in my controller so that I can implement the logging/emailing logic?
推荐答案
也许添加一个监听kernel.exception事件的事件监听器来做到这一点?查看 http://symfony.com/doc/current/book /internals.html#kernel-exception-event 以及 http://symfony.com/doc/current/reference/dic_tags.html#dic-tags-kernel-event-listener
Maybe adding an event listener listening for the kernel.exception event would do it?Check out http://symfony.com/doc/current/book/internals.html#kernel-exception-event along with http://symfony.com/doc/current/reference/dic_tags.html#dic-tags-kernel-event-listener
一个小例子:
1)创建一个自定义侦听器
1) Create a custom Listener
//bundles/Acme/AcmeBundle/Listener/CustomListener.php
namespace Acme\AcmeBundle\Listener;
use Symfony\Component\EventDispatcher\Event;
public class CustomListener {
public function onKernelException(Event $event) {
//Get hold of the exception
$exception = $event->getException();
//Do the logging
// ...
}
}
2)将侦听器添加到您的配置中
2) Add the listener to your config
//config.yml
services:
kernel.listener.your_listener_name:
class: Acme\AcmeBundle\Listener\CustomListener
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
要掌握日志记录或邮件(Swiftmailer)服务,您可以考虑将它们注入侦听器(http://symfony.com/doc/current/book/service_container.html#referencing-injecting-services)
To get hold of the logging or mailing (Swiftmailer) services, you might consider injecting them into the listener (http://symfony.com/doc/current/book/service_container.html#referencing-injecting-services)
这篇关于Symfony2记录404错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!