1

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)

2 Answers 2

2

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')
            );
        }
        // ...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

To handle it in the controller would i put a try/catch in the controller?
Yes. Put a try around the call to getValueByUser and only catch the InvalidArgumentException - you don't want to be catching exceptions that you didn't intend to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.