I have a third party plugin installed on my MVC site.
The plugin allows me to use their services across multiple pages which write to the database (it creates tables as part of the installation/usage).
I setup two folders, Services and Controllers.
The services holds the code to get the plugin to work and take appropriate actions, retrieve data, write back to the database etc.
The controllers folder holds the code for the pages whereby it calls the service from the services folder.
The service holds majority of the code to get it working and the controller calls the service methods. So essentially the controller is very light and the service class is heavy.
My question is in the service I have try catch blocks as when an error occurs it holds it in the try catch block and returns it back to the controller.
Service class example
`public Customer GetCustomer(int id)
{
try
{
// Some code to run
}
catch (SomeException someExcep)
{
throw new SomeException ("some error");
}
catch (OtherException otherExcep)
{
throw new OtherException ("some other error);
}
}`
In order for the controller to return the error back to the user I have the same try catch block in the code for the controller which then displays it back to the frontend user.
`public IActionResult GetCustomer(Customer model)
{
try
{
my service.GetCustomer(model.Id}
}
catch (SomeException someExcep)
{
TempData["message"]= "Something went wrong, try xyz";
}
catch (OtherException otherExcep)
{
TempData["message"]= "Something else happened, try something else";
}
}`
The above code may not be 100% valid but enough to give an example of the try catch structure I have.
I feel I’m duplicating the try catch block between the service and controller.
Is there a way I can return the error back to the user in a better manner or is this the most appropriate way? Or even if the service class just an extra layer that really shouldn’t be there? I just like to ensure I’m picking up best practices where possible.
The reason I have the service class is if I need to upgrade or change anything in future I don’t need to redo the controllers.
The above code may not be 100% valid but enough to give an example of the try catch structure I have.
The reason I have the service class is if I need to upgrade or change anything in future I don’t need to redo the controllers.
I’ve read some articles on MSDN and other search results but no one really covers the area.