Master Front-End Error Collection: Capture JS Exceptions and Resource Failures
This guide explains why front‑end error collection is essential, outlines effective methods such as using window.addEventListener('error', true), details the types of exceptions to monitor—including script errors, resource load failures, HTML hijacking, and CSS issues—and provides practical code snippets for reporting and handling them.
Why collect front‑end code exceptions? To keep users comfortable, efficiently locate online code errors, and let developers sleep peacefully.
Large‑scale internet products need a dedicated front‑end monitoring solution that back‑end monitoring cannot replace. Our company has built a front‑end monitoring script and system, with exception collection as a key component.
Methods to Capture Exceptions
JS exception capture methods, just a few.
try…catch – widely discussed; we use it sparingly.
window.onerror – similar to method 3 but less powerful, so not chosen.
window.addEventListener('error', function(){}, true) – this method is adopted.
Front‑end exceptions consist of two parts: First, exceptions caught by window.onerror (also captured via addEventListener in both bubbling and capturing phases). Second, resource load failures such as <img> and <script> tags with onerror. These cannot bubble to window, but can be captured in the capturing phase, which is why the third parameter of addEventListener is set to true.
Note: To ensure this exception‑collection script runs before any other script errors block it, place it at the very beginning of the page.
Possible Exceptions and Collection Strategies
Resource load failures (styles, images, scripts) – e.g., a 404 JS file.
JS script errors – typical console Error messages.
HTML hijacking – injected tags or scripts by ISPs or other actors.
CSS rendering issues – lost or abnormal page styles.
1. Resource Load Failure
HTTP errors provide little useful info, but 404s can be handled. The onerror callback isn’t triggered; however, addEventListener captures the event, and you can retrieve the failing resource via e.target.outerHTML.
"HttpError at " + (e.target.baseURI || location.href) + " outerHTML:" + e.target.outerHTML2. JS Exceptions
Typical information to collect:
Exception message (e.message) – the primary identifier.
File name where the exception occurred (e.filename).
Line and column numbers (e.lineno, e.colno) – may vary across browsers.
Stack trace (e.error.stack) – contains type, file, line, column for each frame; note Safari/Firefox may only provide the stack.
Device information (window.navigator or userAgent).
Timestamp of the occurrence.
Manually throwing exceptions Developers can use throw with Error objects or other values.
// Using Error objects adds a stack trace similar to system‑thrown errors
throw new Error('Problem description.')
throw Error('Problem description.')
// Throwing raw values overwrites event.error and is not recommended
throw 'Problem description.'
throw nullNote: console.error() and throw new Error() differ – the former logs without interrupting execution and isn’t captured by error events.
The following snippet suppresses console output while still collecting the error data (not recommended for development environments):
window.addEventListener('error', (function(e) {
console.log("-----errorEvent----", e)
e.preventDefault()
}), true);
window.onerror = function(msg, url, line, col, error) {
console.log("------errorInfo---",msg, url, line, col, error)
return true;
}3. Detecting HTML Hijacking
The chosen approach saves the original HTML (via document.documentElement.outerHTML) and compares it with the current page to detect tampering. Because the script must run first, early captures may only contain the <head> section; therefore, capture after window.onload for full page HTML.
// Wrap all I/O operations in try...catch to handle localStorage limits
window.addEventListener("load", function() {
try {
localStorage.setItem("hawkeyeHtml", document.documentElement.outerHTML);
} catch (e) {
// Chrome/Safari: e.name === 'QuotaExceededError'
// Firefox: e.name === 'NS_ERROR_DOM_QUOTA_REACHED'
console.error(e)
}
})4. Page Style Loss
Not yet implemented. The idea mirrors HTML hijacking: capture a screenshot, compare it with a baseline using an algorithm, and flag significant visual differences as style anomalies.
Data Processing Methods
Report to a monitoring server for unified tracking of exception counts and types. Implementation: Use an img tag’s src attribute for reporting, chosen for performance and cross‑domain simplicity.
Print front‑end exceptions on an HTML page for quick diagnosis. Implementation: Store collected data in localStorage (with size control) and provide a dedicated page to retrieve and display the information.
Defect Handling
Obfuscated production code lacks line numbers. Solution: Deploy source maps to restore original line information.
Cross‑origin script errors appear only as “Script error”. Solution 1: Detect this message and guide developers to the console or filter it out. Solution 2: Enable CORS on static resources and add the crossorigin attribute to <script> tags.
Click the original article to access sample code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
