我創建一個服務來獲取一些用戶數據這是正確使用的PHP異常處理/ Symfony2的
class ExampleService{
// ...
public function getValueByUser($user)
{
$result = $this->em->getRepository('SomeBundle:SomeEntity')->getValue($user);
if (!$result instanceof Entity\SomeEntity) {
throw new Exception\InvalidArgumentException("no value found for that user");
}
return $result;
}
}
然後在我的控制器我有
// ...
$ExampleService = $this->get('example_serivce');
$value = $ExampleService->getValueByUser($user);
我應該使用這裏的異常表明在數據庫中沒有找到該用戶的值?
如果我要,我該如何處理取之於$ExampleService->getValueByUser($user)
控制器返回 - 比方說,我只是想設置一個默認值,如果沒有找到(或異常返回)
要處理它在控制器中會把try/catch放在控制器中? – ed209
是的。嘗試圍繞對getValueByUser的調用,並僅捕獲InvalidArgumentException - 您不希望捕獲您不打算訪問的異常。 – Jonathan