2017-09-07 45 views
-1

爲什麼symfony忽略我的自定義標準程序?Symfony 3.3.8忽略自定義標準化程序

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

應用程序/配置/配置.yml

imports: 
    - { resource: parameters.yml } 
    - { resource: security.yml } 
    #- { resource: services.yml } exclude default services file 
    - { resource: "@AppBundle/Resources/config/services.yml" } 

異常輸出

{ 「錯誤」:{ 「代碼」:404, 「消息」: 「未找到」, 「異常」:[{ 「消息」:「的appbundle \實體\用戶對象不。發現 「」 階級 「:」 Symfony的\分量.....

預期的異常輸出

{}

+0

歡迎來到堆棧溢出。請花一些時間閱讀發佈指南,否則您可能會收到反對票。 – catbadger

+0

看起來它與規範化程序無關 - 沒有用戶實體它試圖與 –

+0

@JasonRoman它的異常規範化程序,而不是用戶的規範化程序。我嘗試重新處理異常輸出,但是我得到的異常信息相同的字符串 – andrew357

回答

0

你不應該沒有消除異常。相反,爲這種Exception創建偵聽器,處理它(例如,寫入日誌)並將所需輸出作爲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

你的歸一化是最有可能被忽略,因爲你在你的序列化並沒有註冊。

+0

謝謝,我會試試 – andrew357