Saturday, 15 May 2010

What is an appropriate way to handle or throw exception from service layer of n-tier ASP.Net MVC application? -



What is an appropriate way to handle or throw exception from service layer of n-tier ASP.Net MVC application? -

i have web application 3 layers: web > services > core. services has bunch of business logic helps web build , interpret viewmodels. there might problem in services layer though, , user should pushed error page.

how should error handling implemented in service layer of mvc application? 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 go in isnull block?

generally set exception handling code in controllers. in terminology, assuming the mvc controllers live in "web" layer, , these controllers phone call methods in "service" layer, such "deleteorder" method you've shown. if case, in error handling code in deleteorder, should throw exception:

if (order == null) { throw new invalidoperationexception("specified orderid not exist"); }

this way unhandled exception passed controller, exception handling code lives, , there can log exception , redirect user appropriate error page.

as far how handle exception in controller, have number of options:

use try-catch block each action method implement iexceptionfilter interface on controller class implementing onexception method use built-in handleerrorattribute exception filter create own custom exception handling filter

the 4th method (create own exception filter) robust way go. in here, can add together exception logging, code redirect user appropriate error page based on type of exception thrown.

you can find overview of mvc controller exception handling here.

asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 exception-handling

No comments:

Post a Comment