2014-01-25 50 views
1

我做了一個控制器來提供JSON中的一些webservices,我想在Symfony拋出一個異常(錯誤500)時提供一些錯誤信息,我該怎麼寫這樣的東西?Symfony2:在單個控制器上處理錯誤

webservice的主要目的是更新調用者在POST值中提供的Symfony DB中的信息。

在我的控制器我在JSON中返回響應,我想處理Symfony異常(如提供的值或不符合設計的模式)以返回有關錯誤的詳細信息。

我曾考慮過對每個值進行測試,但編寫並不容易讀取或使用try/catch系統的代碼需要很長時間,但我認爲Symfony已經提供了這樣的功能。

您認爲如何?

THX :)

回答

1

我認爲你應該使用一個EventListener捕獲錯誤並返回正確的響應。

您可以將它放在您的SomethingBundle/EventListener文件夾中,並且您還需要定義一個service以便由Symfony加載。

更多信息:Event Listener

我希望我幫助你,如果你覺得我可能是錯的,讓我知道。祝你好運!

public function onKernelException(GetResponseForExceptionEvent $event) 
{  
    $request = $event->getRequest(); 

    if($this->getBundle($request) == "Something" && $this->getController($request) == "Webservice") 
    { 
     // Do your magic 
     //... 
    } 
} 

private function getBundle(Request $request) 
{ 
    $pattern = "#([a-zA-Z]*)Bundle#"; 
    $matches = array(); 
    preg_match($pattern, $request->get('_controller'), $matches); 

    return (count($matches)) ? $matches[0] : null; 
} 

private function getController(Request $request) 
{ 
    $pattern = "#Controller\\\([a-zA-Z]*)Controller#"; 
    $matches = array(); 
    preg_match($pattern, $request->get('_controller'), $matches); 

    return (count($matches)) ? $matches[1] : null; 
} 

編輯

如果你只是想趕上一個特定的控制器內的錯誤(例如)一個名爲Webservice控制器在SomethingBundle裏面,你必須在做任何事情之前檢查危險這段代碼沒有經過測試,只是一種爲您構建自己的代碼的方法。但是,如果我有什麼問題,告訴我。我想保持我的例子清潔。

+0

是的!這是一個好主意,但我怎麼才能使用這個eventlistener來捕捉異常只爲我的控制器(我的web服務控制器)? –

+1

我在幾個月前做過類似的事情。讓我檢查我的代碼並給你一個例子。我會編輯我的答案。 –

+0

非常感謝,這就是我一直在尋找的:) –

0

使用JsonResponse的Symfony類在沙箱:

use Symfony\Component\HttpFoundation\JsonResponse; 


$data = array(); // array of returned response, which encode to JSON 
$data['error_message'] = 'Bad request or your other error...'); 

$response = new JsonResponse($data, 500); // 500 - response status 
return $response; 
+0

它不是我一直在尋找的,我更多的是在沒有異常模板的情況下通過symfony檢測異常拋出的函數,或者只是在symfony拋出異常以便返回錯誤狀態響應時檢測異常。 –

+1

行,然後用[try catch](http://php.net/manual/ru/language.exceptions.php) –