Reputation: 10124
I have made the following Listener:
namespace AppBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class ExceptionListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
// You get the exception object from the received event
$exception = $event->getException();
$message = array(
'message'=>$exception->getMessage(),
'code'=>$exception->getCode(),
'stacktrace'=>$exception->getTrace()
);
// Customize your response object to display the exception details
$response = new Response();
$response->setContent(json_encode($message,JSON_PRETTY_PRINT));
// HttpExceptionInterface is a special type of exception that
// holds status code and header details
if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
} else {
$response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
$response->headers->set('content/type','application/json');
}
// Send the modified response object to the event
$event->setResponse($response);
}
}
The listener above gets fired when an exception occurs according to my services.yml
:
parameters:
services:
app.exception_listener:
class: AppBundle\EventListener\ExceptionListener
tags:
- { name: kernel.event_listener, event: kernel.exception }
Now what I want to achieve is that when on production to display a different json output from other environments. I mean it won't be wise and a good idea for the end user/api consumer to see the stacktrace.
So do you have any Idea how I will know when I am on production and when I am on development environment?
Upvotes: 1
Views: 1257
Reputation: 3495
You can simply pass kernel.environment
parameter to your class constructor:
app.exception_listener:
class: AppBundle\EventListener\ExceptionListener
arguments: ["%kernel.environment%"]
tags:
- { name: kernel.event_listener, event: kernel.exception }
And then in your class:
class ExceptionListener
{
private $env;
public function __construct($env)
{
$this->env = $env;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
if ($this->env == 'dev') {
// do something
} else {
// do something else
}
}
}
Upvotes: 4