Catch statement does not catch thrown error

前端 未结 3 963
难免孤独
难免孤独 2020-12-01 04:23

For some reason this code gives me an uncaught exception error. It seems the catch block is not catching the error. Are try catch blocks scoped in such a way that I cannot t

相关标签:
3条回答
  • 2020-12-01 04:45

    The reason why your try catch block is failing is because an ajax request is asynchronous. The try catch block will execute before the Ajax call and send the request itself, but the error is thrown when the result is returned, AT A LATER POINT IN TIME.

    When the try catch block is executed, there is no error. When the error is thrown, there is no try catch. If you need try catch for ajax requests, always put ajax try catch blocks inside the success callback, NEVER outside of it.

    Here's how you should do it:

    success: function (result) {
        try {
          result = jQuery.parseJSON(result);
    
          if (!result.data.email) {
             throw ('New exception');
          }
          console.log(result);
          jQuery('.email').html(result.data.email);
        } catch (exception) {
          console.error("bla");
        };
    }
    
    0 讨论(0)
  • 2020-12-01 04:50

    Due to the asynchronous nature of the callback methods in javascript, the context of the function throwing the error is different compared to the original one. You should do this way:

    success: function (result) {
      try {
        result = jQuery.parseJSON(result);
        if(!result.data.email){
          throw ('New exception');
        }
        console.log(result);
        jQuery('.email').html(result.data.email);
      }
      catch(err) {
        // Dealing with the error
      }
    }
    

    I would suggest you to have a look at this excellent article about the (very particular) contexts, closures and bindings in Javascript.

    0 讨论(0)
  • 2020-12-01 04:52

    The problem is that ajax is asynchronous by definition. Your exception does not get thrown from within the $.ajax function, but from the callback function on success (which is triggered at a later time).

    You should give an error: function(data) {} parameter to it as well, to handle server response errors, and furthermore you should place the try/catch block inside the callback function.

    If you really want to catch it outside the callback, then you should consider calling a function rather than throwing an exception, because I don't see how it can be done.

    0 讨论(0)
提交回复
热议问题