What is the appropriate way to handle or throw exceptions from the service level of an n-level ASP.Net MVC application?

I have a web application with three layers: Web> Services> Core. Services have a ton of business logic that helps Web design and interpret viewModels. Sometimes a service level problem may occur, and the user should be redirected to the error page.

How should error handling be performed at the service level of an MVC application? For instance:

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 will be that it is the Null block?

+4
source share
3 answers

Generally, you should put your exception handling code in your controllers. In your terminology, I assume that MVC controllers live at your "Web" level and that these controllers call methods at your "service" level, for example, the "DeleteOrder" method that you specified. If so, in the error handling code in DeleteOrder you should just throw an exception:

 if (order == null) { throw new InvalidOperationException("Specified OrderId does not exist"); } 

Thus, the unhandled exception will be sent to your controller, where the exception handling code lives, and there you can register an exception and redirect the user to the corresponding page with an error.

Regarding exception handling in the controller, you have several options:

The fourth method (create your own exception filter) is probably the most reliable way. Here you can add an exception log, as well as a code to redirect the user to the corresponding error page, depending on the type of exception generated.

You can find a good overview of MVC exception handling here .

+3
source

Throwing a user-friendly exception is the way to go. Your controller should try / catch the code that calls up your service level and act accordingly, redirecting the user to the appropriate page with an error.

In the specific example that you are showing, an OrderNotFoundException exception will be fine.

+1
source

If the service level is built on WCF, use the Fault Contract to report error / exception information.

0
source

All Articles