Handling Exception in the Jquery Post

0

I have this function Javascript ( Post Ajax ) that when it gives exception in post it is passing if (r != "") { . I needed to capture that was an exception and treat it out of if .

JavaScript

function AsyncAlert() {
    $.post("MinhaUrl/AsyncMessage", {}, function (r) {
        if (r != "") {
            mensagemAlert(r);
        }
    });
}

C#

public JsonResult AsyncMessage()
{
    if(TemMensagemNovaAsync())
        return Json(_msgAsync);
    else
        return Json("");
}
  

Consider that I need to catch the exception if I have not been able to connect to the backend. In other words, the url server crashed, the url was not available

What is the best way for me to review this?

Note: My language is C# .

    
asked by anonymous 03.02.2017 / 20:10

1 answer

1

In the documentation for $ .post () , .fail() exists. Use it to do something if an error occurs on the server.

A simple example would be this:

$.post("MinhaUrl/AsyncMessage", function() {
  console.log("sucesso");
}).done(function() {
  console.log("segundo sucesso");
}).fail(function() {
  console.log("error");
}).always(function() {
  console.log("terminou");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
03.02.2017 / 21:13