2013-12-17 20 views
1

我在尋找一個簡單的,愚蠢的解決content-typeapplication/json所有 HTTP錯誤信息(如MethodNotAllowedHttpException等)。FosRestbundle力內容類型的錯誤消息

實施例請求報頭:

Content-Type: application/x-www-form-urlencoded 
Accept: */* 

電流響應頭MethodNotAllowedHttpException):

Content-Type: text/html; charset=UTF-8 

回答

1

如果在報頭中的值的失敗邏輯測試可以丟該錯誤。那麼在你的catch語句中,返回一個json響應。像這樣(未經測試的代碼)

use Symfony\Component\HttpFoundation\JsonResponse; 
use Symfony\Component\HttpFoundation\Request; 

// ..... 

public function myAction(Request $request){ 

    try{ 
     // ... 
     $cType = $request->headers->get('Content-Type'); 
     // logic for testing if the content type is allowed 
     if(!in_array($cType,$allowedArray)){ 
      throw new MethodNotAllowedHttpException(); 
     } 
     // ..... 

    }catch(\Exception $e){ 
     if(get_class($e) == "MethodNotAllowedHttpException"){ 
      $data = array("success"=>false,"message"=>"Method not allowed") 
      return new JsonResponse($data); 
     } 
    } 
} 

這樣你就可以用不同的方式處理不同的異常。我不確定是否要使用內容類型來確定是否拋出異常,但是您可以使用$request->headers->get()

相關問題