Click here to Skip to main content
15,038,345 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm trying to thin down my Controllers, by using a service layer. But I can not workout or find an example of how to handle issues that arise in the service layer.

As an example, I have a controller action Add Item, which has a name and user defined ID.

The code must be unique in the database.

So my controller simply takes the viewmodel and passes it to ItemService.Add()
Inside of Add is the logic to check if the ID exists. If it doesn't the controller needs to send that information back to the user and get them to change their input.

So how do I send that info back to the controller so the error message is stored and the correct view is displayed?

Is there a standard way of doing this, nearly every example I can find shows how to take the logic from the controller a service, but not how to feed errors / exceptions back in.

What I have tried:

I've tried things using out parameters but that seams very 'hacky'.
And special return codes, but that won't be maintainable as the system grows.
Posted
Updated 21-Mar-19 0:48am

1 solution

It's generally done by return types. Either return false from your Add method if it didn't work and show a generic message to the user, or return an enum with values like "Succeeded", "DuplicateID", "InvalidData" etc to specify the specific reason for failure and the controller will then show a message to the user based on that.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900