<?php
namespace App\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use App\Slack\ChannelNotifier;
class KernelExceptionListener implements EventSubscriberInterface
{
protected $environment;
protected $slack;
public function __construct( $environment, ChannelNotifier $slack )
{
$this->environment = $environment;
$this->slack = $slack;
}
public function onKernelException(ExceptionEvent $event)
{
if( $this->environment != 'prod' )
return;
$exception = $event->getThrowable();
if( $exception instanceof HttpExceptionInterface ){
$statusCode = $exception->getStatusCode();
$request = $event->getRequest();
} else {
$statusCode = 500;
$request = false;
}
if($statusCode < 500) // we're not interested in 404s
return;
$message = sprintf('ERROR `%d` (%s) at %s: "%s" in `%s` on `line %s`',
$statusCode,
get_class($exception),
$request ? $request->getUri() : $_SERVER["REQUEST_URI"],
$exception->getMessage(),
$exception->getFile(),
$exception->getLine()
);
$this->slack->send($message);
}
public static function getSubscribedEvents()
{
return array(
KernelEvents::EXCEPTION => array('onKernelException', -128),
);
}
}