0

My controller calls the service layer. The service layer calls a repository or does whatever it does. If I just return a person object for example how do I know it was successfully retreived?

I can only think of two ways to handle this, but wasn't sure if there was another way or if one of these was a more appropriate method for handling this.

  1. Throw an exception in the service layer if there is an issue. The controller can catch the exception and do whatever it needs to do.
  2. Wrap the object I want to return in a ServiceResponse object that has a success boolean and error messages that can be checked in the controller?

Am I way off base?

1
  • 1
    It really doesn't matter so long as the controller understands the response from the service. You can throw an exception, return null, or return some type of wrapper with a status.
    – Dan Wilson
    Apr 8 '20 at 19:09
1

Both of those work. Both require the controller to do more than simply be a controller. They cast it more as an orchestrator.

An alternative is to configure the service layer to pass the results of it’s work somewhere else, like a presentation layer. The controller doesn’t actually need to know what, if anything, happened. It doesn’t have to receive any response at all.

Done this way the controller is actually simply issuing an event. It’s role is over and done with as soon as that’s issued.

The merits of this idea are best understood after studying command query responsibility segregation.

This isn’t to say the other ideas don’t work. But please study this one before you decide it holds no merit for your project.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.