@stacktrace-lite/core
Version:
> Parse, filter, and format JavaScript stack traces with plugins for browsers and Node.js.
61 lines (60 loc) • 2.27 kB
JavaScript
import { parseStack, filterStack, formatStack } from './index.js';
/**
* Installs global browser hooks for `error` and `unhandledrejection`.
*
* @param options - Configuration for filtering, formatting, and handling stacks.
*
* @remarks
* - **`error`**: Fired when a script throws or a resource fails; `ErrorEvent.error`
* may contain an `Error` object when available.
* - **`unhandledrejection`**: Fired when a Promise rejects without a handler;
* the event’s `reason` may be an `Error` or any value.
*
* The handler parses the stack via {@link parseStack}, applies {@link filterStack}
* when provided, and then either calls {@link BrowserHookOptions.onStack} or logs
* a formatted stack using {@link formatStack}.
*
* @example
* ```ts
* installBrowserErrorHooks({
* filter: { preset: 'app-only', include: [/\/src\//] },
* format: 'cli', // or 'html'
* onStack(frames, evt) {
* // send to your telemetry backend
* sendToCollector({ frames, kind: evt.type });
* },
* });
* ```
*/
export function installBrowserErrorHooks(options = {}) {
// Error event
window.addEventListener('error', (event) => {
const err = event.error || new Error(event.message);
handleError(err, options);
});
// Unhandled promise rejection
window.addEventListener('unhandledrejection', (event) => {
const err = event.reason instanceof Error ? event.reason : new Error(String(event.reason));
handleError(err, options);
});
}
/**
* Internal helper to parse, filter, and surface a stack from an error-like payload.
*
* @param err - The error or event that triggered handling.
* @param options - See {@link BrowserHookOptions}.
*/
function handleError(err, options) {
const frames = parseStack(err instanceof Error ? err : String(err));
const filtered = options.filter ? filterStack(frames, options.filter) : frames;
if (options.onStack) {
options.onStack(filtered, err);
}
else {
// Default: log nicely formatted stack
// You can switch format mode (cli, html, etc) as needed
// (In browsers, use 'html' for UI, 'cli' for devtools)
// eslint-disable-next-line no-console
console.log(formatStack(filtered, 'cli'));
}
}