Catch statement does not catch thrown error

前端 未结 3 1044
难免孤独
难免孤独 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: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.

提交回复
热议问题