ed209
ed209

Reputation: 11293

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)

Upvotes: 1

Views: 1794

Answers (2)

Elnur Abdurrakhimov
Elnur Abdurrakhimov

Reputation: 44831

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

Upvotes: 2

Jonathan
Jonathan

Reputation: 325

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. 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.

Upvotes: 1

Related Questions