No Free Time

Because my therapist says I need to let things out

Handling Exceptions in ASP.Net MVC 1

with 3 comments

Here’s a handy way to handle uncaught exceptions in ASP.Net MVC 1.

Make a base controller with the following code:

public class BaseController : Controller

{

ILog log = LogManager.GetLogger(“BaseController”);

string actionName = “”;

string controllerName = “”;

protected override void OnActionExecuting(ActionExecutingContext filterContext)

{

base.OnActionExecuting(filterContext);

actionName = filterContext.ActionDescriptor.ActionName;

controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

}

protected override void OnException(ExceptionContext filterContext)

{

log.Fatal(“Unhandled Exception”, filterContext.Exception);

//Displays a friendly error, doesn’t require HandleError

filterContext.ExceptionHandled = true;

this.View(“Error”, new HandleErrorInfo(filterContext.Exception, controllerName, actionName)).ExecuteResult(this.ControllerContext);

}

}

Then make your other controllers derive from this one and hey presto, friendly(er) error messages and better exception logging in your site.

Sources:

http://geekswithblogs.net/SanjayU/archive/2009/11/09/error-handling-in-asp.net-mvc-1-part-2-of-2.aspx

http://stackoverflow.com/questions/362514/asp-net-mvc-current-action

 

 

Written by tad

November 20th, 2009 at 5:30 am

Posted in .net

Tagged with , ,

3 Responses to 'Handling Exceptions in ASP.Net MVC 1'

Subscribe to comments with RSS or TrackBack to 'Handling Exceptions in ASP.Net MVC 1'.

  1. [...] to VoteHandling Exceptions in ASP.Net MVC 1 (11/19/2009)Thursday, November 19, 2009 from andrewmyhre.wordpress.comHere’s a handy way to handle uncaught [...]

  2. you probably want to not force inheritance. you could do all that function in an attribute, like these…

    public class LogExceptionAttribute : ActionFilterAttribute
    {

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
    if (null != filterContext.Exception)
    {
    ExceptionPolicy.HandleException(filterContext.Exception, “Exception Policy”);
    }
    }

    }

    thomas

    18 Dec 09 at 8:26 am

  3. Love it, thanks for the tip. I haven’t mucked around with custom action attributes much but I’ll definitely give this a go.

    andrewmyhre

    18 Dec 09 at 10:20 pm

Leave a Reply