Home >Web Front-end >JS Tutorial >Capture and Report JavaScript Errors with window.onerror

Capture and Report JavaScript Errors with window.onerror

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2025-02-15 12:57:11776browse

Capture and Report JavaScript Errors with window.onerror

Core points

  • window.onerror is a browser event that is triggered when an uncaught JavaScript error is thrown, providing an easy way to log client errors and report them to the server. All modern browsers support this event, but implementation details vary.
  • The Error object passed to
  • is very valuable for debugging because it contains an error stack trace that provides the source location for each frame when the program errors. However, the stack attribute is non-standard and its implementation is different in different browsers. window.onerror
  • While
  • is widely supported, not all browsers pass Error objects, meaning they cannot retrieve stack trace properties. This limitation can be resolved by wrapping the code in a try/catch block to catch the error and its stack properties. window.onerror
  • After catching the error, the last step is to transfer the error message to the server. This requires setting up a report web service that will receive error data over HTTP, log it to a file and/or store it in a database. If the service is located in a different domain, cross-domain resource sharing (CORS) needs to be supported.

This article is created in collaboration with Sentry. Thank you for supporting the partners who made SitePoint possible.

is a special browser event that is triggered whenever an uncaught JavaScript error is thrown. It is one of the easiest ways to log client errors and report them to the server. This is also one of the main mechanisms for Sentry's client JavaScript integration (raven-js) to work. window.onerror

Listen to

Events by assigning functions to window.onerror onerror

When an error is thrown, the following parameters are passed to the function:
<code class="language-javascript">window.onerror = function (msg, url, lineNo, columnNo, error) {
  // ... 处理错误 ...

  return false;
}</code>

    – Message associated with an error, such as "Uncaught ReferenceError: foo is not defined"
  • msg
  • – URL of the script or document associated with the error, such as "/dist/app.js"
  • url
  • – Line number (if available)
  • lineNo
  • – Column number (if available)
  • columnNo
  • – Error object associated with this error (if available)
  • error
  • The first four parameters tell you which script, row, and column the error occurs. The last parameter, the Error object, is perhaps the most valuable. Let's understand why.

Error object and error.stack

At first glance, the Error object is not special. It contains 3 normalized properties: message, fileName, and lineNumber. These redundant values ​​have been provided to you via

.

The valuable part is a

non-standard attribute: . This stack property tells you the source location of each program frame when an error occurs. Error stack traces can be a key part of debugging. Although non-standard, this property is available in every modern browser. Error.prototype.stack

The following is an example of stack attributes for the Error object in Chrome 46:

<code class="language-javascript">window.onerror = function (msg, url, lineNo, columnNo, error) {
  // ... 处理错误 ...

  return false;
}</code>
It's hard to read, right? The stack property is really just an unformatted string.

The following is what it looks like after formatting:

<code>"Error: foobar\n    at new bar (<anonymous>:241:11)\n    at foo (<anonymous>:245:5)\n    at <anonymous>:250:5\n    at <anonymous>:251:3\n    at <anonymous>:267:4\n    at callFunction (<anonymous>:229:33)\n    at <anonymous>:239:23\n    at <anonymous>:240:3\n    at Object.InjectedScript._evaluateOn (<anonymous>:875:140)\n    at Object.InjectedScript._evaluateAndWrap (<anonymous>:808:34)"
</anonymous></anonymous></anonymous></anonymous></anonymous></anonymous></anonymous></anonymous></anonymous></anonymous></code>
After formatting, it's easy to see how the stack property is crucial in helping debug errors.

There is only one problem: the stack attribute is non-standard, and its implementation in different browsers is also different. For example, the following is the same stack trace in Internet Explorer 11:

<code>Error: foobar
    at new bar (<anonymous>:241:11)
    at foo (<anonymous>:245:5)
    at callFunction (<anonymous>:229:33)
    at Object.InjectedScript._evaluateOn (<anonymous>:875:140)
    at Object.InjectedScript._evaluateAndWrap (<anonymous>:808:34)
</anonymous></anonymous></anonymous></anonymous></anonymous></code>
The format of each frame is not only different, but also has fewer details. For example, Chrome recognizes that the new keyword has been used and has a deeper understanding of eval calls. This is just a comparison between IE 11 and Chrome – other browsers also have different formats and details similarly.

Luckily, there are tools that can normalize the stack attributes so that they are consistent across browsers. For example, raven-js uses TraceKit to normalize error strings. There are stacktrace.js and some other projects.

Browser compatibility

has been around in the browser for a while - you can find it in older browsers like IE6 and Firefox 2. window.onerror

The problem is that each browser implements

in a different way, especially in terms of the number of parameters sent to the onerror listener and the structure of these parameters. window.onerror

The following is a table of parameters passed to onerror in most browsers:

The limited support for onerror in Internet Explorer 8, 9 and 10 may not be surprising. But you might be surprised to find that Safari didn't add support for error objects until Safari 10 (released in 2016). Additionally, legacy mobile devices that still use the stock Android browser (now replaced with Chrome Mobile) still exist and no error object is passed.

If there is no error object, there is no stack trace property. This means that these browsers cannot retrieve valuable stack information from errors captured by onerror.

Use try/catch to provide polyfill for window.onerror

But there is a workaround - you can wrap the code in the application in a try/catch block and catch the errors yourself. This error object will contain the stack attribute we dream of in every modern browser.

Consider the following helper method invoke, which calls a function on an object using a series of parameters:

<code class="language-javascript">window.onerror = function (msg, url, lineNo, columnNo, error) {
  // ... 处理错误 ...

  return false;
}</code>

The following is called again invoke, this time wrapped in try/catch to catch any thrown errors:

<code>"Error: foobar\n    at new bar (<anonymous>:241:11)\n    at foo (<anonymous>:245:5)\n    at <anonymous>:250:5\n    at <anonymous>:251:3\n    at <anonymous>:267:4\n    at callFunction (<anonymous>:229:33)\n    at <anonymous>:239:23\n    at <anonymous>:240:3\n    at Object.InjectedScript._evaluateOn (<anonymous>:875:140)\n    at Object.InjectedScript._evaluateAndWrap (<anonymous>:808:34)"
</anonymous></anonymous></anonymous></anonymous></anonymous></anonymous></anonymous></anonymous></anonymous></anonymous></code>

Of course, it is very cumbersome to do this manually anywhere. You can simplify it by creating a common wrapper utility function:

<code>Error: foobar
    at new bar (<anonymous>:241:11)
    at foo (<anonymous>:245:5)
    at callFunction (<anonymous>:229:33)
    at Object.InjectedScript._evaluateOn (<anonymous>:875:140)
    at Object.InjectedScript._evaluateAndWrap (<anonymous>:808:34)
</anonymous></anonymous></anonymous></anonymous></anonymous></code>

Because JavaScript is single-threaded, you don't need to use wrappers everywhere - just start with each new stack.

This means you need to wrap the function declaration:

  • At the beginning of the application (for example, if you use jQuery, in $(document).ready)
  • In event handler (e.g., addEventListener or $.fn.click)
  • Timer-based callbacks (e.g. setTimeout or requestAnimationFrame)

Example:

<code>Error: foobar
   at bar (Unknown script code:2:5)
   at foo (Unknown script code:6:5)
   at Anonymous function (Unknown script code:11:5)
   at Anonymous function (Unknown script code:10:2)
   at Anonymous function (Unknown script code:1:73)</code>

If this looks like a lot of work, don't worry! Most bug reporting libraries have mechanisms that enhance built-in functions such as addEventListener and setTimeout, so you don't have to call the wrapper utility yourself every time. Yes, raven-js does the same.

Transfer errors to server

OK, you've done your job - you've inserted window.onerror, and you've also wrapped the function in a try/catch block to capture as much error information as possible.

Only one last step is left: transfer the error message to the server. To make this work, you need to set up some kind of reporting web service that will receive your error data over HTTP, log it to a file and/or store it in a database.

If this web service is on the same domain as your web application, just use XMLHttpRequest. In the following example, we use jQuery's AJAX function to transfer data to our server:

<code class="language-javascript">function invoke(obj, method, args) {
    return obj[method].apply(this, args);
}

invoke(Math, 'max', [1, 2]); // 返回 2</code>

Note that if you have to transmit errors across different sources, your reporting endpoint needs to support Cross-domain resource sharing (CORS).

Summary

If you have done this, you now have all the necessary tools to scroll through your own basic error reporting library and integrate it with your application:

    How
  • window.onerror works and its supported browsers
  • How to use try/catch to capture window.onerror Missing stack trace
  • Transfer erroneous data to the server

Of course, if you don't want to bother with all this, there are a lot of commercial and open source tools that can do all the heavy lifting of client reporting for you. (Shh: You might want to try using Sentry to debug JavaScript.)

That's it! Happy error monitoring.

FAQs (FAQ) on using window.onerror to capture and report JavaScript errors

window.onerror How do functions work in JavaScript?

The window.onerror event in JavaScript is a global event handler that is triggered when an error occurs when executing JavaScript code. It is a powerful debugging and error handling tool as it can catch and report uncaught exceptions or runtime errors. When an error occurs, the window.onerror function will be called with five parameters: error message, URL where the error occurred, line number, column number, and Error object.

What is the difference between window.onerror and try-catch in JavaScript?

window.onerror and try-catch are both used for error handling in JavaScript, but they work differently. The try-catch statement allows you to handle the error directly by wrapping the code that may throw an error in a try block and then responding to the error in the catch block. On the other hand, window.onerror is a global event handler that is triggered when an uncaught runtime error occurs. It is a more general error handling mechanism that catches errors that slip from the try-catch block.

How to use window.onerror to catch JavaScript errors?

To use window.onerror, you need to define a function that will be called when an error occurs. This function should take five parameters: error message, URL where the error occurred, line number, column number, and Error object. Inside this function, you can handle errors as needed. For example, you can log errors to the console, send reports to the server, or display messages to users.

window.onerror Can all types of JavaScript errors be caught?

Although window.onerror is a powerful error handling tool, it does have some limitations. It can catch most uncaught runtime errors, but it cannot catch exceptions thrown and caught in the try-catch block. Additionally, certain types of errors, such as network errors or CORS errors, may not trigger the window.onerror event.

How to use an Error object in window.onerror?

The

Error object is the fifth parameter passed to the window.onerror function. It contains information about an error occurred, including error messages, error names, and stack traces. You can use this object to get more detailed information about the error, which is very useful for debugging or error reporting.

What is the stack trace in JavaScript?

Stack trace is a report that provides information about the program execution path when an error occurs. It displays the sequence of function calls that are causing the error, which is very useful for debugging. In JavaScript, you can get a stack trace from an Error object.

How to get stack trace in JavaScript?

In JavaScript, you can get a stack trace from an Error object. When an error occurs, an Error object is created and passed to the window.onerror function. This object has a property called stack that contains the stack trace. You can access this property to get a stack trace.

Can I use window.onerror to report the error to the server?

Yes, you can use window.onerror to report errors to the server. Inside your window.onerror function, you can send a request to the server with an error message. This is very useful for monitoring and debugging, as it allows you to collect and analyze error data from users in real time.

How to use window.onerror to handle CORS errors?

CORS error or cross-domain resource sharing error occurs when a web application tries to access resources from a different domain. These errors are security-related and for security reasons, no details are provided to the window.onerror event handler. However, you can handle these errors by adding an error handler to a specific network request that may cause CORS errors.

What are some best practices for using window.onerror?

When using window.onerror, be sure to handle errors in a way that does not interrupt the user experience. You should avoid displaying technical error messages to users. Instead, consider displaying a friendly error message or silently logging an error. Also, be aware of the performance impact of the error handling code. For example, if you are sending an error report to the server, make sure to do this asynchronously so that it does not block the main thread.

The above is the detailed content of Capture and Report JavaScript Errors with window.onerror. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn