延迟加载 JavaScript 的运行时错误处理?
有谁知道如何对延迟加载的 javascript 进行错误处理?我正在使用一种方法,其中调用 ajax 请求并在全局范围内评估代码。当发生运行时错误时,它会输出文件名作为我的延迟加载脚本,行号是错误行加上我的加载脚本中的 eval 的行号。这不会太糟糕,除非所有的 javascript 文件都被组合到网站各部分的模块中。 javascript 文件本身的 try catch 不会捕获函数的运行时错误。有什么想法吗? Window.onerror 没有提供正确的文件名,因此这是不可能的。我得在它被击中之前抓住它。
我在想也许我可以以编程方式在评估代码中的所有函数中包含尝试捕获(这很丑陋),但由于它是在窗口级别完成的,我不确定如何专门且动态地访问评估代码。当然,如果 javascript 是一个名为“Bob”的对象,我可以访问 window.Bob,但我需要动态地执行此操作。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我解决了这个问题,但这不是最优雅的解决方案。基本上我所做的是:
1. 站点加载后,我查看窗口中的所有对象并将它们推入数组中。这基本上对我的代码说,忽略这些对象。
当我模块化代码时,我会跟踪放入模块中的文件和文件名的长度。
模块化器的最后一行采用 fileLength 数组和 lineLengths 并调用我的错误处理对象中的函数;
错误处理代码在窗口中找到新对象。如果存在,则设置一个属性来匹配 fileLengths 和 fileNames;
递归新对象并添加装饰函数以在它们周围进行 try catch。
当其中一个捕获物被击中时,向上遍历并查找属性。
根据属性计算文件和行号。
根据正确的文件和行号输出新的错误;
是的,丑陋......但它有效。
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.
When I modularize my code I keep track of the length of the files and fileNames being place into a module.
The last line of the modulizer takes the fileLength array and lineLengths and calls a function in my error handling object;
The error handling code finds new objects in window. If they exist, set a property to match fileLengths and fileNames;
Recurse through the new objects and add decorate the functions to have try catches around them.
When one of those catches is hit, traverse upward and find the properties.
Calculate the file and line number based on the properties.
Output the new error based on the correct file and line number;
Yes ugly... but it works.