Friday 21 September 2012

HandleErrorAttribute, Elmah and the Yellow Screen of Death

If you apply the HandleErrorAttribute to an MVC application then it will redirect you to the Error page rather than serve up the Yellow Screen of Death.

But customErrors must be turned on for this to work.

<system.web>
  <customErrors mode="On">
  </customErrors>
</system.web>
Doing this will handle exceptions (e.g. the ExceptionContext's ExceptionHandled property will be set to true).

public class CustomHandleErrorAttribute : HandleErrorAttribute
{
       public override void OnException(ExceptionContext context)
{

          
base.OnException(context);


           // context.ExceptionHandled will return true
if (!context.ExceptionHandled)
return;
          
}

Elmah will only pickup on UNHANDLED exceptions. Under normal circumstances it won't do anything with the UI, it will leave the Yellow Screen of Death intact if one is served. However it will pickup the error and email and log as appropriate.

To use Elmah in conjunction with the HandleErrorAttribute you have to add code to fire off Elmah even though the exception was handled.

A simple example is shown below (with a CustomHandleErrorAttribute)

public
class CustomHandleErrorAttribute : HandleErrorAttribute

{

private readonly ILog log;

public CustomHandleErrorAttribute(ILog log)

{

this.log = log;

}

public override void OnException(ExceptionContext context)

{

// Give the framework a chance to handle the exception

base.OnException(context);

// If the exception was not handled then allow the exception to bubble up - Elmah will catch it

if (!context.ExceptionHandled) return;

// If the exception was handled by the framework then log it for the record

var httpContext = context.HttpContext.ApplicationInstance.Context;

var signal = ErrorSignal.FromContext(httpContext);

signal.Raise(context.Exception, httpContext);

log.Error(context.Exception);

}

}
References:

http://blog.dantup.com/2009/04/aspnet-mvc-handleerror-attribute-custom.html

No comments:

Post a Comment