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?
The middleware UseExceptionHandler can be used to handle exceptions globally. You can get all the details of the exception object (Stack Trace, Inner exception, message etc..) and display them on-screen. You can implement like this.
You should make your services transactional and handle the exceptions in the Controller layer: you may choose Controller Based Exception Handling (Using @ExceptionHandler ) or Global Exception Handling (Using @ControllerAdvice Classes).
In . NET, an exception is an object that inherits from the System. Exception class. An exception is thrown from an area of code where a problem has occurred. The exception is passed up the stack until the application handles it or the program terminates.
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:
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.
Throwing a user-friendly Exception is the way to go. Your controller should try/catch the code that calls your service layer and act accordingly by redirecting the user to an appropriate error page.
In the specific example you show, an OrderNotFoundException would be fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With