我创建一个服务来获取一些用户数据这是正确使用的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