Last active
September 4, 2018 11:30
-
-
Save Shaked/eb30a2f40db75977e93a8a82b56b51ea to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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