views:

23

answers:

0

I'm using ELMAH to log errors. I'm extending HandleError attribute with my own that allows ELMAH to handle all errors. It's my understanding that ELMAH will return Error.aspx to the browser after the error has been logged. That's well and good except for Ajax calls. My client is expecting an Exception returned as JSON if something happens during an Ajax call. For AjaxRequests, how do you get ELMAH to return an exception instead of returning Error.aspx?

Here's how I'm extending HandleError:

public class ProspectorHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext context)
    {
   base.OnException(context);

   if (context.HttpContext.Request.IsAjaxRequest())
   {
   var innerExceptionMessage = (context.Exception.InnerException != null) ? context.Exception.InnerException.Message : String.Empty;

context.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
context.Result = new JsonResult
{
 JsonRequestBehavior = JsonRequestBehavior.AllowGet,
 Data = new
 {
  context.Exception.Message,
  context.Exception.StackTrace,
  innerExceptionMessage
 }
};

context.ExceptionHandled = true;

LogException(context.Exception);
  }
  else
  {
var e = context.Exception;
if (!context.ExceptionHandled   // if unhandled, will be logged anyhow
 || RaiseErrorSignal(e)      // prefer signaling, if possible
 || IsFiltered(context))     // filtered?
 return;

LogException(e);
   }
    }

    private static bool RaiseErrorSignal(Exception e)
    {
        var context = HttpContext.Current;
        if (context == null)
            return false;
        var signal = ErrorSignal.FromContext(context);
        if (signal == null)
            return false;
        signal.Raise(e, context);
        return true;
    }

    private static bool IsFiltered(ExceptionContext context) 
    {
        var config = context.HttpContext.GetSection("elmah/errorFilter") 
                     as ErrorFilterConfiguration;

        if (config == null) 
            return false;

        var testContext = new ErrorFilterModule.AssertionHelperContext(
                                  context.Exception, HttpContext.Current);

        return config.Assertion.Test(testContext);
    }

    private static void LogException(Exception e)
    {
        var context = HttpContext.Current;
        ErrorLog.GetDefault(context).Log(new Error(e, context));
    }
  }
}

When using the above code, I get the following error on the client:

Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerWrapper'.

What this is telling me is that ELMAH is trying to return Error.aspx, which is a strongly typed view and I'm not providing the view the correct data.

How do I get ELMAH to return an exception instead of calling Error.aspx? I'm using jQuery for sending AJAX requests to server.

Thanks

Tom