简体   繁体   English

这是否正确使用PHP / Symfony2中的异常处理

[英]Is this correct use of Exception handling in PHP / Symfony2

I'm creating a service to fetch some user data 我正在创建一个服务来获取一些用户数据

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;
    }
}

Then in my controller I have 然后在我的控制器中我有

// ...
$ExampleService = $this->get('example_serivce');

$value = $ExampleService->getValueByUser($user);

Should I be using an exception here to indicate that no value was found for that user in the database? 我是否应该在这里使用异常指示在数据库中找不到该用户的值?

If I should, how do I handle what is returned from $ExampleService->getValueByUser($user) in the controller - let's say I just want to set a default value if nothing is found (or exception returned) 如果应该的话,我该如何处理控制器中$ExampleService->getValueByUser($user)返回的内容-假设我什么都没找到(或返回异常),只想设置一个默认值

Here is how I do it. 我就是这样做的。 Let's use a user service and a controller as an example. 我们以用户服务和控制器为例。 It's not an exceptional condition in the service layer — it just returns the result without checking it: 它不是服务层中的例外情况 - 它只返回结果而不检查它:

class UserService
{
    public function find($id)
    {
        return $this->em->getRepository('UserBundle:User')->find($id);
    }
}

But in the controllers layer I throw an exception if the requested user not found: 但是在控制器层,如果找不到请求的用户,我会抛出异常:

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

Where you want to handle the exception is kind of up to you, however I would handle it in the controller (and throw it in the model). 您要在哪里处理异常取决于您,但是我会在控制器中处理该异常(并将其扔到模型中)。 I usually try to call a different template if there is an error so as to avoid a bunch of conditionals, but sometimes you just have to put extra logic in your template instead. 我通常尝试在出现错误的情况下调用其他模板,以避免出现一系列条件,但是有时您只需要在模板中添加额外的逻辑即可。

Also, you have to ask yourself if this is really an exceptional condition - it might be easier to return null and handle that return value in your controller. 另外,您还必须问自己这是否真的是例外情况-在控制器中返回null并处理该返回值可能会更容易。 I can't really tell from the data objects (value, service, and user) whether this is something that will happen all the time or not. 我不能从数据对象(值,服务和用户)中真正分辨出这是否会一直发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM