What is an appropriate way to handle or throw exception from service layer of n-tier ASP.Net MVC application?
asp.net-mvc, asp.net-mvc-3, asp.net-mvc-4, exception
Solution
Generally you would put your exception handling code in your controllers. In your terminology, I am assuming the the MVC controllers live in your "Web" layer, and that these controllers call methods in your "service" layer, such as the "DeleteOrder" method you've shown. If this is the case, in your error handling code in DeleteOrder, you should simply throw an exception:
if (order == null)
{
throw new InvalidOperationException("Specified OrderId does not exist");
}
This way the unhandled exception will be passed to your controller, where your exception handling code lives, and there you can log the exception and redirect the user to the appropriate error page.
As far as how to handle the exception in your controller, you have a number of options:
- Use a try-catch block for each action method
- Implement the IExceptionFilter interface on your controller class by implementing the OnException method
- Use the built-in HandleErrorAttribute exception filter
- Create your own custom exception handling filter
The fourth method (create your own exception filter) is probably the most robust way to go. In here, you can add exception logging, as well as code to redirect the user to an appropriate error page based on the type of exception that is thrown.
You can find a good overview of MVC controller exception handling here.
Problem
I have a web application with three layers: Web > Services > Core. Services has a bunch of business logic that helps Web construct and interpret viewModels. Sometimes there might be a problem in the Services layer though, and the user should be pushed to an error page. How should error handling be implemented in the service layer of an MVC application? For example: ``` public void DeleteOrder(int orderId) { var order = _db.Order.FirstOrDefault(c => c.OrderId == orderId); if (order == null) { // error handling } _db.Orders.Remove(order); _db.SaveChanges(); } ``` What would go in that isNull block?