How do I debug my asynchronous, promise based code if the library is swallowing all the exceptions?

懵懂的女人 提交于 2019-11-30 06:44:36

This works with any framework without prior configuration and all recent browsers support this.

Pause On Caught Exceptions: This will actually stop javascript's execution and will take you exactly where the problematic code is, as it's happening.

In Chrome:

  1. Developer Tools,
  2. Sources tab,
  3. Pause on exceptions (stop-like icon) and then
  4. the Pause On Caught Exceptions checkbox

What I ended up doing

I added a sequencing function to my mini library of async helper functions. It basically runs a sequence of "then" calls, except that it adds extra intermediate steps to rethrow any exceptions that end up being caught by the Deferreds. It also accepts an optional error handler to catch the exceptions.

When I call it it looks like this:

go([
    function(){
        return 17;
    },
    function(x){
        //return some stuff
    },
    function(){
         var obj = a_function_that_returns_null_on_IE();
         var x = obj.some_property; //BOOM!
    }
], function(){
    //an optional error handler
});

Another reason that I did things this way is that I have lots of code that needs to work simultaneously with either sync or async code (using Deferred.when to do the chaining). Using my custom function let me use a single, unified syntax and the errors not being captured in the async case is consistent with the sync case, where there are no Deferreds involved. I also think its OK to not capture the error, since unlike in the general case, when I am using "go" I know a-priori what code will be called, so there is no need to capture exceptions for if someone needs to catch them in the future.

Also, using a custom solution gave me the freedom to enforce some personal design preferences :)


In addition to that, I ended up reducing the amount of exceptions I generate myself throughout the code base. Managing exceptions in async code is more annoying then usual and sometimes its simpler to just fallback into handling error conditions by returning null or an error code.

Also, we made sure that any exceptions that we create ourselves are instances of the builtin Error class, intead of other objects. The reason is that the builtin Error class records the line number and stack trace of where it was generated in a kind of cross-browser way.

2016 solution

If you're using native ES Promises do absolutely nothing; Chrome automatically reports uncaught promise rejections in the console.

Notice how the caught one (Second fail) doesn't show anything but the uncaught rejection appears in the console after the code is done running.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!