Skip to content

Instantly share code, notes, and snippets.

@Shaked
Last active September 4, 2018 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shaked/eb30a2f40db75977e93a8a82b56b51ea to your computer and use it in GitHub Desktop.
Save Shaked/eb30a2f40db75977e93a8a82b56b51ea to your computer and use it in GitHub Desktop.
<?php
namespace App;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Psr\Log\LoggerInterface;
class ExceptionListener {
/**
* @var mixed
*/
private $logger;
/**
* @param LoggerInterface $logger
*/
public function __construct(LoggerInterface $logger) {
$this->logger = $logger;
}
/**
* @param GetResponseForExceptionEvent $event
*/
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(Response::HTTP_OK);
// $response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
} else {
$response->setStatusCode(Response::HTTP_OK);
}
$response->headers->set('X-Status-Code', 200);
$this->logger->error($message, [$response]);
// sends the modified response object to the event
$event->setResponse($response);
}
}
servies:
App\ExceptionListener:
tags:
- { name: kernel.event_listener, event: kernel.exception }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment