Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for asp.net mvc error handling [closed]

I'm looking for a standard way to handle errors in asp.net mvc 2.0 or 3.0

  • 404 error handler
  • Controller scope exception error handler
  • Global scope exception error handler
like image 452
noname.cs Avatar asked Dec 24 '10 02:12

noname.cs


People also ask

Which is the best way to handle errors in net?

You can handle default errors at the application level either by modifying your application's configuration or by adding an Application_Error handler in the Global. asax file of your application. You can handle default errors and HTTP errors by adding a customErrors section to the Web. config file.

Is try catch block really needed in MVC application when we have exception filters in MVC?

We have try catch block for error handling, But in case of MVC we have exception filters. In such case we can handle errors at filter level. i.e. by using exception filters.


1 Answers

For controller scope errors try using a custom Exception attribute i.e.

public class RedirectOnErrorAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {

        // Don't interfere if the exception is already handled
        if(filterContext.ExceptionHandled)
        return;

        //.. log exception and do appropriate redirects here

     }
}

Then decorate the controllers with the attribute and error handling should be yours

[RedirectOnError]
public class TestController : Controller
{
     //.. Actions etc...
}

Doesn't help if the error is with the routing though - i.e. it can't find a controller in the first place. For that try the Application Error handler in Global.asax i.e.

 protected void Application_Error(object sender, EventArgs e)
 {
      //.. perhaps direct to a custom error page is here
 }

I don't know if it's 'best practice' though. Does work.

like image 192
Crab Bucket Avatar answered Sep 30 '22 15:09

Crab Bucket