Thursday, March 31, 2011

What are some of the strategy to handle unhandled exception in asp.net mvc applications?

I would like to know some of the strategy/practice you deal with to handle unhandled exceptions in ASP.NET MVC.

In short I want to avoid the yellow screen whenever any error happens and show a error consistent error message to the visitor.

I mean do you write a controller for this which shows the appropriate error page or you go some other way like writing an httpmodule and trapping the error at a global level.

Any inputs in this direction is appreciated.

From stackoverflow
  • Try the HandleError attribute.

  • Don't use the exception handling article that you linked to. It's an old article where they didn't have the HandleError attribute added in the framework. Use the HandleError attribute. It was added in preview 4.

    rajesh pillai : I'll check this. Thanks for the input.
  • Using the HandleError attribute is the way to go. Here is a small sample which I use to handle Ajax calls from JQuery, ExtJs, and others.

    On your controller

    public class DataController : Controller
    {    
        [HandleError(ExceptionType = typeof(ArgumentException), View = "ErrorAjax")]
        public void Foo(string x, string y)
        {    
            if (String.IsNullorEmpty(x))
                throw new ArgumentException("String cannot be empty!");
    
                // Call your layers or whatever here
                AnotherCall();
        }
    }
    

    Then on your view (ErrorAjax). Notice it's strongly typed (HandleErrorInfo)

    <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<HandleErrorInfo>" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Sorry Dude!</title>
    </head>
    <body>
        <div>
            <!-- be creative here-->
            Sorry, an error occurred while processing your request.
            Action = <%= ViewData.Model.ActionName %>
            Controller = <%= ViewData.Model.ControllerName %>
            Message = <%= ViewData.Model.Exception.Message %>
    
        </div>
    </body>
    </html>
    

    A couple of gotchas

    1. Check your web.config and make sure customErrors mode="On"
    2. For starters, create the View under the Shared folder
    Simon_Weaver : 3. also make sure your error page doesn't return any errors. For one must use HandlerErrorInfo as its model - as shown above, but there are of course other possible sources for errors.

0 comments:

Post a Comment