开发者

Run time error handling on lazy loaded javascript?

Does anyone have any ideas how to do error handling on lazy loaded javascript? I am using an approach in which开发者_高级运维 an ajax request is called and the code is eval'd in global scope. When a runtime error is struck, it spits out the filename as my lazy loading script and the line number is the error line plus the line number of my eval in my loading script. This wouldn't be so bad except all the javascript files get combined into modules for sections of the site. A try catch around the javascript file itself wont catch runtime errors of the functions. Any ideas? Window.onerror doesn't provide the correct filename so it is out of the question. I need to catch it before it is hit.

I was thinking maybe I could programmatically include try catches around all the functions within the eval'd code (which is ugly), but since it is done at the window level I am not sure how to access the eval'd code specifically and dynamically. Sure if the javascript is an object named "Bob" I can access window.Bob but I need to do it dynamically.


I solved the issue, however it is not the most elegant solution. Essentially what I do is this:
1. After the site loads I look at all the objects that are in window and push them into an array. This basically says to my code, ignore these objects.

  1. When I modularize my code I keep track of the length of the files and fileNames being place into a module.

  2. The last line of the modulizer takes the fileLength array and lineLengths and calls a function in my error handling object;

  3. The error handling code finds new objects in window. If they exist, set a property to match fileLengths and fileNames;

  4. Recurse through the new objects and add decorate the functions to have try catches around them.

  5. When one of those catches is hit, traverse upward and find the properties.

  6. Calculate the file and line number based on the properties.

  7. Output the new error based on the correct file and line number;

Yes ugly... but it works.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜