2016-10-28 8 views
1

JSFレスポンスを返すJSONレスポンスを返すSymfony3でカスタム例外を作成して、後でそれをJavaScriptで処理できるようにしたいと考えています。symfony3 JSONレスポンスを返すカスタム例外

可能かどうか知っていますか?

+0

あなたは適切なヘッダーを持つ新しい応答(json_encode(...))を返すことができます。 – Andrew

+0

それは確かに私が今の間したことです。しかし、私は本当にJsonコードを返す単純なページとJsonコードを返す例外の間のコードの違いを作ることができるようにしたいと思います... – Fab

+0

あなたは例外ハンドラ、標準のJSON応答、例外バブリングクラス(例外ハンドラクラスのための言葉)と私は他の方法があると確信しています。 – Andrew

答えて

0

このように、新しい例外ハンドラクラスを作成します。

namespace AppBundle\Subscriber; 

use Symfony\Component\EventDispatcher\EventSubscriberInterface; 
use Symfony\Component\HttpFoundation\JsonResponse; 
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; 

class ExceptionSubscriber implements EventSubscriberInterface 
{ 

    /* ... */ 

    public static function getSubscribedEvents() 
    { 
     return [ KernelEvents::EXCEPTION => 'onKernelException' ]; 
    } 

    public function onKernelException(GetResponseForExceptionEvent $event) 
    { 
     $customResponse = new JsonResponse(['error' => 'My custom error message']); 
     $event->setResponse($customResponse); 
    } 

} 

アプリ/設定/ services.ymlで新しいサービスを登録することを忘れないでください:

app.exception_subscriber: 
    class: AppBundle\Subscriber\ExceptionSubscriber 
    tags: 
     - { name: kernel.event_subscriber }