show exception error on callback AJAX

1

I have this ajax call:

$.ajax({
    method: "GET",
    url: "/Shipper/getFullAddress",
    data: {
        postalCode: value
    },
    dataType: 'json',
    success: function(data) {
        $('#AddressStreet').val(data.AddressStreet);
        $('#AddressNeighborhood').val(data.AddressNeighborhood);
        $('#AddressCity').val(data.AddressCity);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(jqXHR);
        console.log(textStatus);
        console.log(errorThrown);
    }
})

Call this method:

[AjaxCall]

public JsonResult getFullAddress(string postalCode) {
    try {
        var address = getAddressByZipCode(postalCode);
        return Json(address, JsonRequestBehavior.AllowGet);
    } catch (System.Exception ex) {
        return Json(ex.Message);
    }
}

I wanted to show the exception message in my view, but my call returns this:

    
asked by anonymous 09.03.2017 / 15:21

1 answer

1

If you check the html that is being returned in the responseText, you will notice that this is an error page because of AllowGet, which you did not post when you handled the error.

The correct one would be:

public JsonResult getFullAddress(string postalCode) {
try {
    var address = getAddressByZipCode(postalCode);
    return Json(address, JsonRequestBehavior.AllowGet);
} catch (System.Exception ex) {
    **return Json(ex.Message, JsonRequestBehavior.AllowGet);**
}
}

With this you solve the error problem, but if you want to display the message that is being returned, you will need to review your code, because as you are returning a text in the response, it will not go through the "error" function. ajax since there was no error.

    
10.03.2017 / 18:07