show Exception error on return of AJAX call

Asked

Viewed 536 times

1

I have this call ajax:

$.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);
    }
})

who calls 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 flame returns this: inserir a descrição da imagem aqui

  • It seems that json is wrong somewhere

  • yes, and I don’t know where it could be.

  • click on that 65,524 that appears on the console to see what happened on json

  • Man, this code of yours, I don’t think it’s gonna behave the way you expect it to. There in javascript, as you treat the error on the server, will not fall into the "error" function of ajax. I will post an answer explaining the error.

1 answer

1


If you check the html that is being returned in responseText, will notice that this is an error page because of Allowget, which you did not put when it comes to the error.

The right thing 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 in case you want to display the message being returned, you will need to review your code, because as you are returning a text in the reply, you will not go through the "error" function of ajax since no error actually occurred.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.