【问题标题】:Is this correct use of Exception handling in PHP / Symfony2这是在 PHP / Symfony2 中正确使用异常处理吗
【发布时间】:2011-11-21 20:17:29
【问题描述】:

我正在创建一个服务来获取一些用户数据

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) 返回的内容 - 假设我只想在未找到任何内容(或返回异常)的情况下设置默认值

【问题讨论】:

    标签: php exception exception-handling symfony


    【解决方案1】:

    这是我的做法。让我们以用户服务和控制器为例。这不是服务层的异常情况——它只是返回结果而不检查它:

    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')
                );
            }
            // ...
        }
    }
    

    【讨论】:

      【解决方案2】:

      你想在哪里处理异常取决于你,但是我会在控制器中处理它(并将它扔到模型中)。如果出现错误,我通常会尝试调用不同的模板以避免一堆条件,但有时您只需要在模板中添加额外的逻辑即可。

      此外,您必须问自己这是否真的是一个例外情况 - 返回 null 并在控制器中处理该返回值可能会更容易。我无法从数据对象(价值、服务和用户)中真正判断这是否会一直发生。

      【讨论】:

      • 要在控制器中处理它,我会在控制器中放置一个 try/catch 吗?
      • 是的。尝试调用 getValueByUser 并仅捕获 InvalidArgumentException - 您不想捕获您不打算捕获的异常。
      猜你喜欢
      • 2012-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-14
      • 2012-08-25
      • 1970-01-01
      • 2018-07-09
      相关资源
      最近更新 更多