2015-09-04 19 views
0

我試圖在我的控制器上設置一個錯誤處理程序來捕捉任何可能導致我的頁面出現故障的東西。例如:在這種情況下,我試圖捕捉一旦我的方法調用帶有錯誤參數的外部API時可能發生的任何錯誤,但除了給我典型的ClientException in Middleware.php line 69: Client error: 400這不是我所知正是爲了。任何建議都將非常值得讚賞或更好的方式來處理Silex中的錯誤。Silex - 我的錯誤處理程序不起作用

private function getSIS($url, $session, Application $app) 
{ 
    $message = "You don't have permission to access this!"; 

    if($app['security']->isGranted('ROLE_SUPER_ADMIN')) 
    { 
     $client = new Client(['base_uri' => 'https://***********.ca/api/SIS/']); 
     if (!empty($session)) 
      $response = $client->get($url, ['query' => 'session=' . $session]); 
     else 
      $response = $client->get($url); 
     return $response; 
    } 

    $app->error(function (\Exception $e, $code) { 
     switch($code) { 
      case 404: 
       $message = 'The requested page could not be found'; 
       break; 
      default: 
       $message = 'We are sorry, but something went terribly wrong.'; 
     } 

     return new Response($message); 
    }); 

    return new Response($message); 
} 

回答

1

$app->error方法可能需要放置在控制器操作的上下文之外。我不知道到底如何,你有你的應用程序結構,但也許嘗試把錯誤塊權之前$app->run();

$app->error(function (\Exception $e, $code) use ($app) { 
    switch($code) { 
     case 404: 
      $message = 'The requested page could not be found'; 
      break; 
     default: 
      $message = 'We are sorry, but something went terribly wrong.'; 
    } 

    return new Response($message, $code); 
}); 

$app->run(); 
+0

你暗示,錯誤塊將是一個全球性的錯誤處理程序? –

+0

從'$ app-> get','$ app-> match'等引發的任何異常應該落入該$ app-> error'回調。所以是的,我相信這將是一個全局錯誤處理程序。 – ooXei1sh