[英]Is this correct use of Exception handling in 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)
返回的內容-假設我什么都沒找到(或返回異常),只想設置一個默認值
我就是這樣做的。 我們以用戶服務和控制器為例。 它不是服務層中的例外情況 - 它只返回結果而不檢查它:
class UserService
{
public function find($id)
{
return $this->em->getRepository('UserBundle:User')->find($id);
}
}
但是在控制器層,如果找不到請求的用戶,我會拋出異常:
class UserController
{
public function viewAction($id)
{
$user = $this->get('user.service')->find($id);
if (!$user) {
throw $this->createNotFoundException(
$this->get('translator')->trans('user.not_found')
);
}
// ...
}
}
您要在哪里處理異常取決於您,但是我會在控制器中處理該異常(並將其扔到模型中)。 我通常嘗試在出現錯誤的情況下調用其他模板,以避免出現一系列條件,但是有時您只需要在模板中添加額外的邏輯即可。
另外,您還必須問自己這是否真的是例外情況-在控制器中返回null並處理該返回值可能會更容易。 我不能從數據對象(值,服務和用戶)中真正分辨出這是否會一直發生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.