2

I tried doing it with a global attribute

edit: Updated with final solution

public class HandleAndLogErrorAttribute : HandleErrorAttribute
{
    private static readonly ILog log = Log<HandleAndLogErrorAttribute>.Create();

    public override void OnException(ExceptionContext filterContext)
    {
        if (!filterContext.ExceptionHandled)
        {
            log.Error("Unhandled exception", filterContext.Exception);
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new { Message = filterContext.Exception.Message, StackTrace = filterContext.Exception.StackTrace }.AsJson();
                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Response.Clear();
                filterContext.HttpContext.Response.StatusCode = 500;
                filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;      
            }
            else
                base.OnException(filterContext);
        }
    }
}

The problem is that MVC will ignore the Result and render the error page, if I set filterContext.ExceptionHandled = true; it will not ignore the Result but it will return code 200 instead of 500 so my generic error handler on the client wont detect the error. I cant return 200 because then my success methods for the calls will fire with unexpected behavior.

Any ideas?

Anders
  • 17,306
  • 10
  • 76
  • 144
  • 1
    Updated with code to get it to work with IIS also, otherwise it only works with dev.server. – Anders Oct 15 '12 at 10:18

0 Answers0