WYSIWYG

http://kufli.blogspot.com
http://github.com/karthik20522

Friday, September 28, 2012

Handling Unhandled Exception Asp.NET MVC

Well, having unhandled exception is bad in the first place but displaying user a default IIS broken exception page or the yellow broken code page is even worse. Not a good user experience. But as all code/software there is always bugs and all ways a edge case that breaks unexpectedly. These unhandled expections can be handled in controller level in Asp.NET MVC. Following is a code snipped of handling errors and routing the user to a more user friendly error page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class HandleErrorAttribute: System.Web.Mvc.HandleErrorAttribute
{
 public override void OnException(ExceptionContext filterContext)
 {
  string askerUrl = filterContext.RequestContext.HttpContext.Request.RawUrl;
 
  Exception exToLog = filterContext.Exception;
  exToLog.Source = string.Format("Source: {0}{1}Requested Path: {2}{1}",
    exToLog.Source, Environment.NewLine, askerUrl);
 
  //log your message somewhere
  Handle(exToLog);
 
  filterContext.ExceptionHandled = true;
  filterContext.Result = new System.Web.Mvc.RedirectResult("~/Error");
 
  base.OnException(filterContext);
         }
}
 
namespace YourNameSpace
{
    [HandleError]
    public class YourController : Controller
    {
        //controller code - Actions
    }
}


In the above code, once the error is handled it's redirected to an Error Page. A user friendly error page such as this from clipthetrip.com

Labels: , ,