Search code examples
javascripttry-catchthrow

Javascript Catch, but Still Throw Error


I've built a javascript function that merges multiple ajax functions into a single request. With each request, there is almost always a callback function. The bundled function calls the callback functions one at a time.

I've surrounded these with a try catch to prevent one function from preventing the other functions from running. However, I would still like the browser to notify me about javascript errors. How can I do this?

I've set an example of what I'm trying to do up here.

The code from the jsfiddle link above:

<script>
function doSomeStuff() {
    for (var i in arguments) {
        try { 
            arguments[i].apply(this);
        }
        catch (e) {
            throw e;
        }
    }
}

doSomeStuff(function() { console.log("i'm an apple"); }, 
    function() { imnotavariable = test; },
    function() { console.log("i'm an apple too"); });
</script>

Summary of Question: How do I catch an error, while still reporting it to the browser?


Solution

  • If you want the loop to finish (i.e. call all your functions), you can't throw the error within it. One approach of achieving what you want is to save the error and throw it after the loop, i.e.

    var error = null;
    for (...) {
      try {
        ...
      }
      catch(e) {
        error = e;
      }
    }
    if(error != null) { throw error; }
    

    This will only propagate the last error though. If you want to catch all of the errors that occur, you would need to merge them into a single one that you can then again throw.

    Alternative solution by Tom

    You can also set a timeout on the throw so that it doesn't interfere with the execution of the functions.

    function doSomeStuff() {
      for (var i in arguments) {
        try { 
          arguments[i].apply(this);
        }
        catch (e) {
          setTimeout(function() { throw e; }, 100);
        }
      }
    }