Custom Exception Listener in Symfony2

June 3, 2016 | No Comments | Programming | event listener monolog pushover Symfony2

The common task in web development is handling and monitoring exception with various tools. In this article I can show how to handle and log errors in Symfony2.  For this task we will use our custom exception listener.

For example, we have Pushover Handler in Monolog library and we want to receive push notification about every exception except 404 errors.

First, we should create our custom exception listener. Let’s name it CustomExceptionListener:

<?php
//src/AppBundle/Listener/CustomExceptionListener.php
 
namespace AppBundle\Listener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
 
class CustomExceptionListener
{
    private $logger;
 
    public function __construct($logger)
    {
        $this->logger = $logger;
    }
 
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();
 
        if(!$exception instanceof NotFoundHttpException)
        {
            $this->logger->info(sprintf('Error message: %s',$exception->getMessage()));
        }
    }
 
}

Now, we should add proper service in config.yml file:

#src/AppBundle/Resources/config/config.yml
services:
    app.exception_listener:
      class: AppBundle\Listener\CustomExceptionListener
      arguments: [@logger]
      tags:
            - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
            - { name: monolog.logger, channel: custom }

Last, add our handler to pushover in Symfony2 Monolog configuration:

#app/config/config.yml
monolog:
    handlers:
        pushover:
            type:  pushover
            level: debug
            title: "Monolog Message"
            user: "your-pushover-user-key"
            token: "your-pushover-app-key"
            channels: ['custom']

That’s it. Now you can receive push notification about your errors on your phone.

pushover


About the Author / Artem Zhuravlev

Artem Zhuravlev. Web developer. Blog writer.

Need help with your website ? Contact with me by email infzanoza@gmail.com for services of experienced web developer.

Follow @infernosquad

LEAVE A COMMENT