Get the actual Javascript Error object with window.onerror

浪尽此生 提交于 2019-11-28 17:45:40

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.

this is now possible in some browsers. The spec was updated to include the actual error with stacktrace as the 5th parameter.

the problem is that not every browser supports this yet, so you could do something like this:

window.onerror = function(message, filename, lineno, colno, error)
{
    if(error != null)
    {
        //handle the error with stacktrace in error.stack
    }
    else
    {
        //sadly only 'message', 'filename' and 'lineno' work here
    }
};

Modern browsers fully support the HTML 5 draft spec for ErrorEvent and window.onerror. In both of these browsers you can either use window.onerror, or (amazingly!) bind to the 'error' event properly:

// Only Chrome & Opera pass the error object.
window.onerror = function (message, file, line, col, error) {
    console.log(message, "from", error.stack);
};
// Only Chrome & Opera have an error attribute on the event.
window.addEventListener("error", function (e) {
    console.log(e.error.message, "from", e.error.stack);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!