1

I am working on asp mvc, in which i have jquery datatable and some chart elements, i am fetching all of items by ajax calls.

now i need to redirect user if any of ajax (datatable json data and image for chart)call encounter exception. Now i am using datatable's error callback that give me required html that am generating when exception has occurred, but at the same time along with datatable i am sending 7 more jquery call to controllers whose output is depend on datatable's result,so these 7 call trap in infinite loop. now how do i stop this processing at server side if my datatble's function encounter error.

Thanks in advance.

Pavan Tiwari
  • 3,077
  • 3
  • 31
  • 71

3 Answers3

4

Handle the error Event of your jQuery Ajax & do whatever you want to do i that function.

$.ajax(
      {
          success: function (result) {

              });
          },
          error: function (x, e) {
           //Write you code here
              alert(x.readyState + " " + x.status + " " + e.msg);
          }
      });
Kapil Khandelwal
  • 15,958
  • 2
  • 45
  • 52
1

I did it using an aspx page in my MVC3 project as:

<customErrors mode="RemoteOnly" defaultRedirect="Error.aspx">
</customErrors>

Hope this helps

TRR
  • 1,637
  • 2
  • 26
  • 43
1

In AJAX Error Handling you should always take care of both sides: server side and client side. You need to decide what to happen in each side.

Kapil Khandelwal's answer is great but it only covers the client side.

I also encourage you to read this Q/A: ASP.NET MVC Ajax Error handling

It's always useful to define a generic or specific Error Handler and decorate the methods which return JsonResult or response to any kind of AJAX call. Something like:

public class JsonErrorHandler : ActionFilterAttribute 
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
        {
            // Log the Error
            // Do necessary things...

            filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;

            filterContext.Result = new JsonResult()
            {
                //JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new
                {
                    filterContext.Exception.Message,
                    filterContext.Exception.StackTrace
                }
            };

            filterContext.ExceptionHandled = true;
        }
    }
}

Then you use it like:

[JsonErrorHandler]
public JsonResult GetMyData(...)
{
    .
    .
    .
}
Community
  • 1
  • 1
Tohid
  • 6,175
  • 7
  • 51
  • 80