0

Im using MVC on server side and calling a function via jQuery.Ajax sending json type. the function results with exception. i want to invoke/trigger the error result function of the Ajax, what should i send back with the return JSON function? for the example, let's say the return JSON is triggered from the catch section.

MVC Function

public JsonResult Func()
{       
    try
    {               
        var a = 0;
        return Json(a, JsonRequestBehavior.AllowGet);              
    }
    catch (Exception ex)
    {
        FxException.CatchAndDump(ex);
        return Json(" ", JsonRequestBehavior.AllowGet);
    }
}

JavasScript call

$.ajax({
    url: '../Func',
    type: 'GET',
    traditional: true,
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    success: function (data) {
        alert('s');
    },
    error: function (data) {
        alert('e');
    }
});
Adrian Forsius
  • 1,437
  • 2
  • 19
  • 29
eyalewin
  • 360
  • 4
  • 20

3 Answers3

0

Quoting from this answer:

The error callback will be executed when the response from the server is not going to be what you were expecting. So for example in this situations it:

HTTP 404/500 or any other HTTP error message has been received data of incorrect type was received (i.e. you have expected JSON, you have received something else).

The error callback will be executed when the response from the server is not going to be what you were expecting. So for example in this situations it:

HTTP 404/500 or any other HTTP error message has been received data of incorrect type was received (i.e. you have expected JSON, you have received something else). In your situation the data is correct (it's a JSON message). If you want to manually trigger the error callback based on the value of the received data you can do so quite simple. Just change the anonymous callback for error to named function.

function handleError(xhr, status, error){

    //Handle failure here

 }

$.ajax({

  url: url,
  type: 'GET',
  async: true,
  dataType: 'json',
  data: data,

 success: function(data) {
     if (whatever) {
         handleError(xhr, status, ''); // manually trigger callback
     }
     //Handle server response here

  },

 error: handleError
});
Community
  • 1
  • 1
Miguel Mota
  • 20,135
  • 5
  • 45
  • 64
0

error callback is invoked when HTTP response code is not 200 (success) as well as when response content is not comply to expected contentType which is json in your case.

So you have to either send HTTP header with some failure response code (e.g. 404) or output non-json response content. In the latter case you can simply output empty string:

return "";
hindmost
  • 7,125
  • 3
  • 27
  • 39
0

If you want to trigger an error in AJAX, but still know "why" it was triggered so you can customize the error message, see this post:

https://stackoverflow.com/a/55201895/3622569

Ben in CA
  • 688
  • 8
  • 22