I wrote a logger for my HTTP client. Register a response interceptor and the console shows the method, URL, status and duration for each request. Once it worked, I wondered how to look beyond my own machine. Locally I can open the console and see what happened. How do I collect that information when the problem happens in a user’s browser? The following afternoon I searched listen to console logs in web app.1
Later, in AssetMan, the logger could print a red 401 for an asset-list load while the page ultimately received a 200. The first response triggered a token refresh, the retry succeeded, and the list displayed normally. Counting every red 401 as a failed user operation would give me the wrong failure count.2
What record does a failed save actually leave?
Suppose a user clicks Save and the API returns HTTP 500. The page checks response.ok and displays “Unable to save right now. Please retry.” Here fetch returned a Response normally. Unless the code throws separately, an uncaught-exception monitor may receive no exception at all. Conversely, the API may return 200 and the page may throw TypeError while processing the response. In either case the user might report “Save is broken.”34
What does a collection SDK need from a web page?
A common API design is to call init once when the application starts, selecting the automatic sources and where records should go. For an error that business code has handled but that still deserves investigation, call captureException(error) explicitly. Sentry’s browser SDK, for example, records some console calls and Fetch/XHR requests as breadcrumbs, traces of what happened before an error. A console.warn can supply context in an exception report. Storing it as a separate log is another setting. Sentry separates these choices: dsn selects the receiving project, beforeBreadcrumb filters breadcrumbs, and beforeSend can change or drop an error event before dispatch.5
Try a small experiment. Save this block as index.html and the implementation in the next section as monitor.js in the same directory. Run python3 -m http.server 8000 there and open http://localhost:8000/. Leave out missing-asset.json so the static server actually returns 404. The example SDK passes every record to onEvent. Here it stores them in an array so you can see exactly what arrived locally.
<!doctype html>
<meta charset="utf-8">
<button id="run">模拟一次加载</button>
<button id="inspect">在控制台查看记录</button>
<script src="monitor.js"></script>
<script>
const records = [];
const monitor = initMonitor({
consoleLevels: ['log', 'warn', 'error'],
captureErrors: true,
captureFetch: true,
onEvent: event => records.push(event)
});
document.querySelector('#run').onclick = async () => {
console.warn('开始加载资产');
await fetch('./missing-asset.json'); // 收到 404,Promise 仍然兑现
try {
await fetch('./assets.json', { signal: AbortSignal.abort() });
} catch {
// 这次请求由调用方主动取消,业务代码已处理这次拒绝。
}
setTimeout(() => { throw new Error('列表渲染失败'); }, 0);
Promise.reject(new Error('列表刷新失败')); // 故意留下未处理的拒绝
};
document.querySelector('#inspect').onclick = () => console.table(records);
</script>
Why does a single initMonitor(...) call start listening?
The browser loads monitor.js first and defines the function when it reaches function initMonitor(...) { ... }. Then it runs the HTML’s const monitor = initMonitor({...}). The parentheses to the right of the equals sign mean call this function now. Following console.warn makes the two moments clear.
The full implementation loops over log, warn and error. When level === 'warn', console[level] means console.warn. Expanded on its own, that iteration looks like this. It is shown for comparison with the implementation and does not need to be pasted again.
const originalWarn = console.warn.bind(console); // 初始化时:先保存旧函数
console.warn = (...args) => { // 初始化时:把新函数装到原位置
originalWarn(...args); // 点按钮后:照常显示警告
emit('console', { level: 'warn', args }); // 点按钮后:再记一条日志
};
“Wrapping” means a new function takes over the call, calls the old function internally and adds a collection step. When the page opens, only the assignment has run. records is still empty. When the button calls console.warn('开始加载资产'), execution enters the new function with args equal to ['开始加载资产'] (“starting asset load”). emit calls the supplied onEvent, and only then does records.push(event) add the warning to the array.
The other two switches also take effect during initialization. With captureErrors: true, the function immediately calls window.addEventListener(...). The browser remembers the callback until the page encounters an error. With captureFetch: true, the function replaces window.fetch with a version containing the recording logic. Only then does it return { captureException: ... }. The monitor variable on the left stores that return value so application code can report errors explicitly later.
How does the SDK capture the three types of records?
Install monitor.js once at page startup. Console and Fetch calls can be observed by wrapping their original methods. The browser provides events for uncaught script exceptions. emit adds the time and hands the record to the integrating application. The example receiver only writes to an array so it does not itself call the monitored console or fetch.
function initMonitor({ consoleLevels = [], captureErrors, captureFetch, onEvent }) {
function emit(type, fields) {
try {
onEvent({ time: Date.now(), type, ...fields });
} catch {
// 本地接收函数写入失败时,业务代码仍然继续运行。
}
}
// 1. 保留原来的控制台输出,同时记住级别和原始参数。
for (const level of consoleLevels) {
const original = console[level].bind(console);
console[level] = (...args) => {
original(...args);
emit('console', { level, args });
};
}
// 2. 全局异常、未处理的 Promise 拒绝和主动上报共用事件格式。
function recordError(type, reason) {
const message = reason instanceof Error ? reason.message : String(reason);
emit(type, { message, stack: reason instanceof Error ? reason.stack : undefined });
}
if (captureErrors) {
window.addEventListener('error', event => {
if (event instanceof ErrorEvent) recordError('script-error', event.error ?? event.message);
});
window.addEventListener('unhandledrejection', event => {
recordError('unhandled-rejection', event.reason);
});
}
// 3. 包装 Fetch:和上面的 console.warn 一样,先保存,再替换。
if (captureFetch) {
const originalFetch = window.fetch.bind(window);
window.fetch = async (input, options) => { // 页面以后调用 fetch,会先进入这里
const url = input instanceof Request ? input.url : String(input);
const start = performance.now(); // 读一次时钟,与结束读数的差值就是经过的毫秒数。
let response;
try {
response = await originalFetch(input, options); // 仍由原方法真正发请求
} catch (error) {
emit('fetch-rejected', { url, message: error?.message ?? String(error),
durationMs: performance.now() - start });
throw error;
}
if (response.status >= 400) {
emit('http-error', { url, status: response.status,
durationMs: performance.now() - start });
}
return response;
};
}
return { captureException: error => recordError('handled-error', error) };
}
Follow the button’s fetch('./missing-asset.json') call. It enters the new function assigned to window.fetch. That function sends the request with originalFetch, calls emit('http-error', ...) after receiving 404, and finally uses return response to give the same response back to the button code. Calling window.fetch(...) there would re-enter the wrapper, which is why the original method was saved in advance.
Click “模拟一次加载” (simulate one load), then “在控制台查看记录” (inspect records in the console). You should see five records. First is the application’s console warning. Of the two request records, http-error has status 404, while fetch-rejected came from a deliberate abort and has no HTTP status. You will also find script-error with “列表渲染失败” (list rendering failed) and unhandled-rejection with “列表刷新失败” (list refresh failed). Catching the final Promise rejection in application code keeps it out of the global rejection event. To retain it, call monitor.captureException(error) inside catch (error) and its type becomes handled-error.34
How far can an SDK installed on the page see?
| Source | What this example can see | What it can miss |
|---|---|---|
| Console | Calls to the selected console.log/warn/error methods on the current page after installation, including third-party libraries running on that page | Browser-generated DevTools diagnostics such as resource-load failures. Earlier output and previously saved original methods also bypass the wrapper. |
| JS exceptions | Script errors delivered to this window, unhandled Promise rejections and explicitly reported errors | The application must explicitly report exceptions it handles. Workers and iframes have separate execution environments, and a listener on the current window is not a global listener for them. Details of cross-origin script errors may also be limited.4 |
| Requests | Calls through the current window.fetch after installation. HTTP 4xx/5xx responses and Fetch rejections are separate records. Both deliberate aborts and actual loss of connectivity may reach the rejection branch. | XHR needs separate instrumentation for open/send and completion, errors and aborts. Image and stylesheet loads bypass this Fetch wrapper.67 |
| Business outcome | The application knows which attempt ultimately succeeded and can emit a separate event there | A request can fail then succeed on retry, and red console output need not affect the page. Automatic records alone cannot give the save success rate. |
If I maintain both the parent page and an embedded iframe, the child can collect its own records and send summaries to the parent with window.postMessage(). The parent listens for message. Specify the parent’s target origin when sending, and check event.origin and event.source when receiving. This combines records from two windows provided the child cooperates.8
If I can change the page, do I need a browser extension?
On r/webdev, serg06 described users occasionally waiting a long time for a third-party service. They already had a Splunk server but could not see how long the request took in the user’s browser.9
If you can change your page, initialize the SDK at the application entry point and send browser-measured request durations to a receiver. In the example, onEvent is where to change destinations. For real reporting, select only needed fields, strip URL query parameters, batch reports and keep the original Fetch for the reporting channel or exclude the collector’s URL. That prevents a failed report from triggering another report.6
The observation point determines what is visible. The browser loads images and stylesheets itself, and a page can read some timing information via Resource Timing. For cross-origin resources, detailed timing depends on the other server’s response headers. An SDK also cannot infer which SQL statement ran from a client-side 500. Correlate server logs by request ID to trace that far.7
A browser extension suits a different job, such as a tester authorized to observe a site without the ability to change its deployment. An extension’s webRequest API can listen to the request lifecycle on permitted sites. declarativeNetRequest serves a different purpose: giving the browser rules to block or redirect matching requests. Measuring endpoint latency for your own website needs no request modification.10
I also looked at extension APIs with other purposes. For an extension that lets testers manually collect incident information, menus can provide a context-menu entry and alarms can schedule a later task. Two other APIs deal with the browser itself: management queries installed extensions, while browserSettings reads and writes browser settings that extensions are permitted to control.1112
If the test already listens, does the page need the same listeners?
Playwright can deliver browser events to the test process. page.on('console') observes messages printed by the page, page.on('pageerror') collects uncaught exceptions, and page.on('response') can inspect HTTP status. Its requestfailed documentation has an easily missed qualification: “A request will only be considered failed when the client cannot get an HTTP response from the server”. For a 500 test, inspect the response. For a connectivity failure, wait for the request-failed event.13
Here is an example test. Assume the site has a configured baseURL and loads its asset list from /api/assets. Deliberately returning 500 isolates the question of whether the page handles that result. Installing the listener before navigation also captures startup exceptions.
import { test, expect } from '@playwright/test';
test('资产接口返回 500 时显示重试提示', async ({ page }) => {
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.route('**/api/assets', route => route.fulfill({
status: 500,
contentType: 'application/json',
body: JSON.stringify({ message: 'temporary failure' })
}));
await page.goto('/assets');
await expect(page.getByRole('alert')).toHaveText('暂时无法加载,请重试');
expect(errors).toEqual([]);
});
The first assertion checks what the user sees. The second checks for uncaught exceptions up to the point when the message appears. Merely printing a line inside a listener does not fail the test. To verify that the application reported an error, check what the report receiver received. The test process follows only the browser it controls. To investigate a problem an ordinary user encountered yesterday, page-level collection had to be enabled at the time.
Looking back at AssetMan, I would keep the logger’s 401 and separately record that the list ultimately loaded. There was another, subtler example: one version of the HTTP client constructed a Response with status 424 when fetch threw, and a downstream logger printed it. Preserving which layer saw the response lets you distinguish a server-supplied status from a client-generated one.1 Code example for request logging and retries (English)
This reading later led to Sentry’s Native, PowerShell and Android documentation. After the Native SDK I searched capture all errors in c and opened a C++ question instead. The asker called a native Windows function from Java through JNI and the entire VM crashed. The answer’s catch (...) handles C++ exceptions that reach that handler. If a fault terminates the process outright, reconstructing what happened requires native crash collection.1415
The PowerShell example resembles explicitly calling captureException: a script can report an error record it already caught in catch. The Android docs divide troubleshooting into two steps. First attach preceding breadcrumbs or a screenshot to see what happened before the error. If class and method names in the release stack trace were obfuscated, supply that build’s mapping file to make the stack readable again.161718
For what a user saw before the error and why a UI might freeze, see how session replay works (English) and distinguishing slow requests from slow JavaScript.
References
Footnotes
-
Cai, B. [S2thend]. (2025, May 13). Express HTTP Client [source, commit
7357757]. GitHub. Timing requests and constructing a 424 response, Logger. ↩ ↩2 -
CaiBorui. (2025, May 21). Add support for express http handler [AssetMan commit
54933d5, author’s local Git copy].frontend/src/utils/ExpressHttpHandler.js, response interceptor registration and 401 retry branch. Filed under the May 14 research date. The integration example is from the following week. ↩ -
MDN contributors. (n.d.). Using the Fetch API. MDN Web Docs. Checking response status. ↩ ↩2
-
MDN contributors. (n.d.). Window: error event; Window: unhandledrejection event. MDN Web Docs. Synchronous script errors, Unhandled Promise rejections. ↩ ↩2 ↩3
-
Sentry. (n.d.). Breadcrumbs; Capturing errors and events. Sentry Docs. Automatic breadcrumbs, Explicit error capture, Filtering before dispatch. ↩
-
Sentry. (n.d.). Session Replay configuration. Sentry Docs. Network details. ↩ ↩2
-
MDN contributors. (n.d.). PerformanceResourceTiming. MDN Web Docs. Cross-origin timing information. ↩ ↩2
-
MDN contributors. (n.d.). Window: postMessage() method; Window: message event. MDN Web Docs. Sending messages, target origins and security considerations, Receiving messages. ↩
-
serg06. (2023, March 24). How do you do frontend/client-side logging? [forum post]. Reddit, r/webdev. Paragraphs 1–2, occasional third-party request delays and client logging. ↩
-
MDN contributors. (n.d.). webRequest; declarativeNetRequest. MDN Web Docs. Request events and permissions, Declarative rules. ↩
-
MDN contributors. (n.d.). menus; alarms. MDN Web Docs. Creating menu items, Scheduling tasks. ↩
-
MDN contributors. (n.d.). management; browserSettings. MDN Web Docs. Querying installed extensions, Browser settings. ↩
-
Microsoft. (n.d.). Page. Playwright Docs. on('requestfailed'), Note, sentence 2, on('pageerror'), on('console'). ↩
-
Obediah Stane. (2008, November 25). C++ catching all exceptions [question]. Stack Overflow. Java/JNI calling context, final paragraph of the question. Greg D. (2008, November 25). Answer to “C++ catching all exceptions”. Stack Overflow.
catch (...)example at the start of the answer. ↩ -
Sentry. (n.d.). Sentry for Native. Sentry Docs. C/C++ SDK and crash capture. ↩
-
Sentry. (n.d.). Usage for PowerShell. Sentry Docs. Capturing Errors, reporting handled error records. ↩
-
Sentry. (n.d.). Enriching Events for Android. Sentry Docs. Breadcrumbs, Context and Screenshots. ↩
-
Sentry. (n.d.). Enhance Error Reporting for Android. Sentry Docs. ProGuard and DexGuard mapping files. ↩