2015-06-11 17 views
7

Sto usando FOSRestBundle con Symfony 2 per implementare un'API REST in formato JSON.Come si personalizza il formato delle eccezioni con FOSRestBundle e Symfony 2?

voglio tutte le eccezioni API per essere restituiti in un determinato formato JSON come questo:

{ 
    "success": false, 
    "exception": { 
     "exceptionClass": "SomeNastyException", 
     "message": "A nasty exception occurred" 
    } 
} 

Come posso fare questo?

Ho cercato di armeggiare con ExceptionController, ma la logica sembra troppo complicata per essere facilmente sovraccaricata.

+0

avete risolto questo? Ho lo stesso problema –

risposta

10

Nota: Funziona solo per FOSResBundle < 2.0. Per FOSResBundle> = 2.0, utilizzare Normalizzatori di eccezioni, vedere examples.

È possibile scrivere un gestore di wrapper di eccezioni personalizzato come in docs. Nel tuo caso:

<?php 
//AppBundle\Handler\MyExceptionWrapperHandler.php 
namespace AppBundle\Handler; 

use FOS\RestBundle\Util\ExceptionWrapper; 
use FOS\RestBundle\View\ExceptionWrapperHandlerInterface; 

class MyExceptionWrapperHandler implements ExceptionWrapperHandlerInterface { 

    public function wrap($data) 
    { 
     /** @var \Symfony\Component\Debug\Exception\FlattenException $exception */ 
     $exception = $data['exception']; 

     $newException = array(
      'success' => false, 
      'exception' => array(
       'exceptionClass' => $exception->getClass(), 
       'message' => $data['status_text'] 
      ) 
     ); 

     return $newException; 
    } 
} 

esempio app/config/config.yml

fos_rest: 
    routing_loader: 
     default_format: json 

    view: 
     view_response_listener: force 
     exception_wrapper_handler: AppBundle\Handler\MyExceptionWrapperHandler 

    exception: 
      enabled:    true 

Risposta:

{"success":false,"exception":{"exceptionClass":"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException","message":"Not Found"}} 
+1

Penso che questa risposta potrebbe non essere più valida. FOSRestBundle non include più una classe di gestione wrapper di eccezioni o un'interfaccia da quello che posso vedere. – JackalopeZero

+0

Questo è deprecato dalla versione 2.0 di FOS Rest. Un'altra idea? –

+0

Sì, è deprecato perché ora dipende dal serializzatore.Quindi dovresti trovare il modo in cui modificare l'eccezione usando il tuo serializzatore. Vorrei aggiungere un esempio, ma temo che la risposta sarà troppo grande. Ad esempio normalizer per JMSSerializerBundle https://github.com/FriendsOfSymfony/FOSRestBundle/blob/2.0/Serializer/Normalizer/ExceptionHandler.php –

5

ho atterrato su questa discussione un certo numero di volte gli ultimi giorni. Per chiunque altro nella mia situazione in cui si utilizza V2 del pacchetto, è possibile trovare la seguente risorsa sull'aggiornamento di FOSRestBundle utile.

Riguarda l'uso del serializzatore al posto di ExceptionWrapperHandlerInterface.

https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/UPGRADING-2.0.md

  • L'opzione exception_wrapper_handler config è stato rimosso. Utilizzare invece i normalizzatori .

Prima:

config.yml

fos_rest: 
    view: 
     exception_wrapper_handler: AppBundle\ExceptionWrapperHandler 

Handler

namespace AppBundle; 

class ExceptionWrapperHandler implements ExceptionWrapperHandlerInterface 
{ 
    public function wrap($data) 
    { 
     return new ExceptionWrapper(array('status_code' => 'foo')); 
    } 
} 

Dopo (se si utilizza il serializzatore Symfony):

services.yml

services: 
    app_bundle.exception_normalizer: 
     class: AppBundle\Normalizer\ExceptionNormalizer 
     tags: 
      - { name: serializer.normalizer } 

normalizzatore

namespace AppBundle\Normalizer; 

use Symfony\Component\Serializer\Normalizer\NormalizerInterface; 

class ExceptionNormalizer implements NormalizerInterface 
{ 
    public function normalize($object, $format = null, array $context = array()) 
    { 
     return array('status_code' => 'foo'); 
    } 

    public function supportsNormalization($data, $format = null) 
    { 
     return $data instanceof \My\Exception; 
    } 
} 
Problemi correlati