为什么symfony忽略我的自定义规范化器?
的src /的appbundle /串行器/正规化/ ExceptionNormalizer.php
<?php
namespace AppBundle\Serializer\Normalizer;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* Class ExceptionNormalizer
*/
class ExceptionNormalizer implements NormalizerInterface
{
/**
* {@inheritdoc}
*/
public function normalize($object, $format = null, array $context = array()): array
{
return [];
}
/**
* {@inheritdoc}
*/
public function supportsNormalization($data, $format = null): bool
{
return $data instanceof \Exception;
}
}
的src /的appbundle /资源/配置/ services.yml
services:
...
app.normalizer.exception:
class: AppBundle\Serializer\Normalizer\ExceptionNormalizer
tags:
- { name: serializer.normalizer }
应用/配置/ config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
#- { resource: services.yml } exclude default services file
- { resource: "@AppBundle/Resources/config/services.yml" }
异常输出
{&#34;错误&#34;:{&#34;代码&#34;:404,&#34;消息&#34;:&#34;未找到&#34;,&#34;异常&# 34;:[{&#34; message&#34;:&#34; AppBundle \ Entity \ User object not found。&#34;,&#34; class&#34;:&#34; Symfony \ Component .. ...
预期的异常输出
{}
答案 0 :(得分:1)
你不应该规范异常。相反,为这种异常创建侦听器,处理它(例如,写入日志)并将所需的输出作为Response返回。
class ExceptionListener
{
/** @var LoggerInterface */
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
$e = $event->getException();
if ($e instanceof ValidationException) {
$event->setResponse(new JsonResponse(['error' => $e->getViolations()], 422)
} elseif ($e instanceof DomainException) {
$this->logger->warning('Exception ' . get_class($e) , ['message' => $e->getMessage()]);
$event->setResponse(
new JsonResponse(['error' => 'Something is wrong with your request.'], 400);
} elseif ($e instanceof NotFoundHttpException) {
$event->setResponse(new JsonResponse(['error' => 'Not found.'], 404);
} else {
$event->setResponse(new JsonResponse(['error' => $this->translator->trans('http.internal_server_error')], 500);
}
}
}
更新services.yml
app.exception_listener:
class: Application\Listeners\ExceptionListener
arguments: ['@domain.logger']
tags:
- { name: kernel.event_listener, event: kernel.exception }
进一步阅读有关听众和活动的信息https://symfony.com/doc/current/event_dispatcher.html
您的规范化器很可能被忽略,因为您没有在序列化程序中注册它。