[英]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
: 根据我的
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. 现在我想要实现的是在生产时从其他环境显示不同的json输出。 I mean it won't be wise and a good idea for the end user/api consumer to see the stacktrace.
我的意思是最终用户/ api消费者看到堆栈跟踪是不明智的。
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: 您可以简单地将
kernel.environment
参数传递给类构造函数:
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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.