1

I am using the following code in a MVC controller to process exceptions that occurs during an ajax call.

protected override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                filterContext.Result = new JsonResult
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { Error = true, Msj = filterContext.Exception.Message }
                };
            }
}

I want to process the error in the front-end using the errorCallback function of the object $http (AngularJs). The problem is the following, if I set filterContext.ExceptionHandled = true;

Angular does not recognize the error and executes the success function. If I set filterContext.ExceptionHandled = false; Angular will execute the error function, but asp.net will replace the object "Data" of the json result with the usual yellow error page.

Is it possible to avoid that asp.net replaces the response?

Any help will be appreciated?

Regards

3
  • Are you very sure your if condition is returning true ? Commented May 3, 2016 at 16:40
  • Yes, completely. I did properly configure Angular headers: $http.defaults.headers.post["X-Requested-With"] = "XMLHttpRequest"; Commented May 3, 2016 at 16:49
  • Take a look at the answer i posted. Commented May 3, 2016 at 17:19

1 Answer 1

1

You are missing 2 things.

  1. You need to set the ExceptionHandled property to true so that the framework will not do the normal exception handling procedure and return the default yellow screen of death page.

  2. You need to specify the Response status code as 5xx ( Error response). The client library will determine whether to execute the success callback or error callback based on the status code on the response coming back.

This should work.

protected override void OnException(ExceptionContext filterContext)
{
    if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
    {
        filterContext.Result = new JsonResult
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet,
            Data = new { Error = true, Msj = filterContext.Exception.Message }
        };
        filterContext.HttpContext.Response.StatusCode = 500;
        filterContext.ExceptionHandled = true;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

It's true. Thank you very much !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.