Ayorus
Ayorus

Reputation: 507

How to process ajax exception with MVC and angularjs?

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

Upvotes: 1

Views: 148

Answers (1)

Shyju
Shyju

Reputation: 218702

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;
    }
}

Upvotes: 1

Related Questions