-1

I have the next example using jQuery:

try{

   $.post(url,data, function(response){
       throw 'Exception';
   });
}catch(e){
      alert('Error'); 
}

But the line: alert('Error') is never executed. What is happening here?

CStff
  • 361
  • 2
  • 10

1 Answers1

2

You're exception is thrown asynchronously, so the exception will not be caught.

The correct way to deal with this is

$.post(url,data, function(response){
   throw 'Exception';
}).catch(function(ex){
    alert('Error'); 
});
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • note that this require jquery 3.0 or later – CStff Apr 24 '17 at 13:47
  • @CStff other way round, as of 3.0 it is `.fail(func)`. (The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead. - from https://api.jquery.com/jquery.post/) – Jamiec Apr 24 '17 at 13:53
  • @CStff thanks for sharing. Did it work? – Jamiec Apr 24 '17 at 15:47
  • I tried my code using "catch" and "fail' but seems that they don't handle exceptions, only errors related to the connection. Even "always" is ignored. – CStff Apr 24 '17 at 15:54