Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Try/catch inside JQuery $.ajax call

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #176161
    fooman
    Participant

    I’m trying to throw an error from jquery’s ajax callbacks without much luck. I read that’s because it’s asynchronous and the try/catch loses scope by the time the callback is reached.

    I made a pen to show this issue

    If you open up the inspector, click the button, you’ll see that the error thrown is uncaught.
    How do you handle this? I enjoy throwing errors because they can all back caught back where the original function call was made, but it seems that this doesn’t work with async functions such as $.ajax.

    So, has anyone ever dealt with this? Any advice?

    #176266
    noahgelman
    Participant

    I believe the reason why your try/catch doesn’t work is because code the Ajax success/error callbacks are outside the scope of the try/catch. The success/error callbacks can’t even read variables stated outside the Ajax call.

    Here is an example: http://codepen.io/anon/pen/Adewv

    So how do you better track what function sends out errors?

    I haven’t used it before but I believe you can use .ajaxError() to help track these things. Here is jQuery’s page on it. Maybe it’ll help you out.

    http://api.jquery.com/ajaxError/

    #176369
    noahgelman
    Participant

    Scope is scope. If a variable doesn’t work, try/catch won’t either.

    I think code pen automatically intercepts and returns success for any Ajax request used without actually sending it out. Probably to prevent any weird hacking tricks.

    I would suggest making your own internet. With Blackjack. And Hookers.

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.