简体   繁体   中英

Symfony: Custom Listener Change response on different environments

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?

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
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM