使用window.onerror获取实际的Javascript Error对象 [英] Get the actual Javascript Error object with window.onerror

查看:405
本文介绍了使用window.onerror获取实际的Javascript Error对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javascript有这个很好的回调 window.onerror 。跟踪任何错误都很方便。但是,它调用错误名称,文件名和行。从 try ... catch 语句中获取实际的错误对象当然不是那么丰富。
实际的错误对象包含更多的数据,所以我试图得到这个。不幸的是,当您开始使用异步代码时, try ... catch 语句不正常。



有没有结合和获得两个世界最好的方式?我最初寻找一种方式来获得 onerror 块中触发的最后一个错误,但是看起来JS不存储。 p>

任何线索?

解决方案

如果你指的是堆栈跟踪错误对象,那么AFAIK,这是不可能的。



简单的原因是堆栈跟踪与执行上下文相关,其中运行时异常(使用try ... catch ...最终处理)被创建或抛出(使用新的错误() throw )。



而当 window.onerror 被调用时,它会在不同的上下文中调用。



您可以通过在<$ c $中查看 window.event (FF上不可用)获得一些里程c> onerror 处理程序。


Javascript has this great callback window.onerror. It's quite convenient to track any error. However, it calls with the error name, the file name and the line. It's certainly not as rich as getting the actual error object from a try...catch statement. The actual error object contains a lot more data, so I am trying to get that. Unfortunately, try...catch statement do not work fine when you start having async code.

Is there a way to combine and get the best of both worlds? I initially looked for a way to get the last error triggered within an onerror block, but it looks like JS doesn't store that.

Any clue?

解决方案

If you're referring to stack trace of the error object, then AFAIK, this is not possible.

Simple reason being that a stack trace is related to an execution context in which runtime exceptions (handled with try...catch...finally) were created or thrown (with new Error() or throw).

Whereas when window.onerror is invoked, it is called within a different context.

You can get some mileage by inspecting window.event (not available on FF) in your onerror handler.

这篇关于使用window.onerror获取实际的Javascript Error对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆