1

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?

1 Answer 1

1

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

A little example:

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

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)

Sign up to request clarification or add additional context in comments.

2 Comments

This is the route I ended up going. Now I just need to figure out the service injection piece. I'm using GetResponseForExceptionEvent as the concrete event type - is that the right one to use?
GetResponseForExceptionEvent is the one you have to use for the exception. And may I suggest checking if the error is 404? Otherwise all exception will be mailed to you (if you want that, you can use the Monolog configuration for it).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.