From a551e88f925aa161b62801d99eac0a9db0a2635f Mon Sep 17 00:00:00 2001 From: "Eric J. Smith" Date: Tue, 1 Dec 2026 19:06:12 -0600 Subject: [PATCH 1/2] Keep events when core plugins or serialization hit bad data - parseQueryString/getCookies: decode safely, split on the first "=", match exclusions on the decoded key, use "" for missing values and skip empty keys. - prune/stringify: drop values whose getter, toJSON or Proxy throws instead of throwing; cap nested toJSON calls by depth; track only ancestors for cycle detection (arrays and errors included) so shared, non-circular references are kept. - EventPluginManager: a throwing plugin is logged with its name and the error, and the event continues instead of being cancelled. - EventExclusionPlugin: logs without a level are cancelled when the source's minimum level is off; exception type exclusions also apply to @simple_error. - DuplicateCheckerPlugin: de-duplicate @simple_error events. --- .../references/plugins.md | 2 +- .../references/troubleshooting.md | 4 + packages/core/src/Utils.ts | 156 ++++++---- .../core/src/plugins/EventPluginManager.ts | 12 +- .../plugins/default/DuplicateCheckerPlugin.ts | 6 +- .../plugins/default/EventExclusionPlugin.ts | 6 +- packages/core/test/Utils.test.ts | 270 +++++++++++++++++- .../test/plugins/EventPluginManager.test.ts | 101 +++++-- .../default/DuplicateCheckerPlugin.test.ts | 36 +++ .../default/EventExclusionPlugin.test.ts | 40 ++- 10 files changed, 545 insertions(+), 88 deletions(-) diff --git a/.agents/skills/exceptionless-javascript/references/plugins.md b/.agents/skills/exceptionless-javascript/references/plugins.md index 1d49378a..8ecd3e88 100644 --- a/.agents/skills/exceptionless-javascript/references/plugins.md +++ b/.agents/skills/exceptionless-javascript/references/plugins.md @@ -55,7 +55,7 @@ await Exceptionless.startup((config) => { - Lower `priority` values run earlier. - Setting `context.cancelled = true` stops later plugins and prevents submission. -- Plugin errors are caught by `EventPluginManager`; the event is cancelled to avoid sending partially processed data. +- Plugin errors are caught by `EventPluginManager`, logged with the plugin name and error message, and the event continues through the remaining plugins. A throwing plugin does not cancel the event; set `context.cancelled = true` to drop it. A failing `startup` or `suspend` is logged the same way and does not stop other plugins. - Keep plugins small. Prefer plugins for cross-cutting enrichment or filtering, not business logic. - Be careful adding user, request, headers, cookies, query, or body data. Read [data-exclusions.md](data-exclusions.md) first. diff --git a/.agents/skills/exceptionless-javascript/references/troubleshooting.md b/.agents/skills/exceptionless-javascript/references/troubleshooting.md index 4e287503..56305daa 100644 --- a/.agents/skills/exceptionless-javascript/references/troubleshooting.md +++ b/.agents/skills/exceptionless-javascript/references/troubleshooting.md @@ -38,6 +38,10 @@ If expected data is absent from an event, check `includePrivateInformation`, `in If expected events are missing, check synced settings and client-side filters such as `@@log:*`, `@@error:*`, `@@usage:*`, and custom plugins that set `context.cancelled = true`. +A log minimum level of `off` for a source (for example `@@log:*` = `off`) also drops logs submitted without a level. Exception type settings such as `@@error:TypeError` apply to both `@error` and `@simple_error` data, including inner errors. + +If a custom plugin throws, the client logs `Error running plugin ""` and keeps processing the event. Enable `config.useDebugLogger()` to see these messages; the default logger discards them. + ## Source Anchors - `packages/core/src/queue/DefaultEventQueue.ts` diff --git a/packages/core/src/Utils.ts b/packages/core/src/Utils.ts index 1d64be44..2456f645 100644 --- a/packages/core/src/Utils.ts +++ b/packages/core/src/Utils.ts @@ -18,15 +18,38 @@ export function getCookies(cookies: string, exclusions?: string[]): Record = {}; for (const pair of pairs) { - const parts = pair.split("="); - if (!exclusions || !isMatch(parts[0], exclusions)) { - result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]); + const [key, value] = splitKeyValuePair(pair); + if (key && (!exclusions || !isMatch(key, exclusions))) { + result[key] = value; } } @@ -312,11 +335,11 @@ export function endsWith(input: string, suffix: string): boolean { * 2. If the value is a function or unsupported type it will be return undefined. * 3. If the value is an array, it will be pruned to the specified depth. * 4. If the value is an object, it will be pruned to the specified depth and - * a. If the object is a Circular Reference it will return undefined. + * a. If the object is a Circular Reference (it contains itself, including through arrays and errors) it will return undefined. Repeated references that are not circular are kept. * b. If the object is a Map, it will be converted to an object. Some data loss might occur if map keys are object types as last in wins. * c. If the object is a Set, it will be converted to an array. * d. If the object contains prototype properties, they will be picked up. - * e. If the object contains a toJSON function, it will be called and it's value will be normalized. + * e. If the object contains a toJSON function, it will be called and it's value will be normalized. Nested toJSON calls count against the depth. * f. If the object is is not iterable or cloneable (e.g., WeakMap, WeakSet, etc.), it will return undefined. * g. If a symbol property is encountered, it will be converted to a string representation and could overwrite existing object keys. * 5. If the value is an Error, we will treat it as an object. @@ -324,6 +347,7 @@ export function endsWith(input: string, suffix: string): boolean { * 7. If the value is a Regexp, Symbol we will convert it to the string representation. * 8. BigInt and other typed arrays will be converted to a string unless number type works. * 9. All other values will be returned as undefined (E.g., Buffer, DataView, Promises, Generators etc..) + * 10. If reading a value throws (e.g., a throwing getter or toJSON, or a revoked Proxy), that value will return undefined and the rest of the object is kept. */ export function prune(value: unknown, depth: number = 10): unknown { function isUnsupportedType(value: unknown): boolean { @@ -358,7 +382,7 @@ export function prune(value: unknown, depth: number = 10): unknown { return false; } - function normalizeValue(value: unknown): unknown { + function normalizeValue(value: unknown, toJSONDepth: number): unknown { function hasToJSONFunction(value: unknown): value is { toJSON: () => unknown } { return value !== null && typeof value === "object" && typeof (value as { toJSON?: unknown }).toJSON === "function"; } @@ -399,8 +423,12 @@ export function prune(value: unknown, depth: number = 10): unknown { } if (hasToJSONFunction(value)) { - // NOTE: We are not checking for circular references or overflow - return normalizeValue(value.toJSON()); + // Each toJSON call counts against the depth so a toJSON that returns itself or another toJSON object terminates. + if (toJSONDepth > depth) { + return undefined; + } + + return normalizeValue(value.toJSON(), toJSONDepth + 1); } return value; @@ -413,13 +441,7 @@ export function prune(value: unknown, depth: number = 10): unknown { return value; } - function pruneImpl( - value: unknown, - maxDepth: number, - currentDepth: number = 10, - seen: WeakSet = new WeakSet(), - parentIsArray: boolean = false - ): unknown { + function pruneImpl(value: unknown, maxDepth: number, currentDepth: number = 10, ancestors: Set = new Set(), parentIsArray: boolean = false): unknown { if (value === null || value === undefined) { return value; } @@ -428,55 +450,83 @@ export function prune(value: unknown, depth: number = 10): unknown { return undefined; } - if (isUnsupportedType(value)) { - return undefined; - } - - const normalizedValue = normalizeValue(value); - if (typeof normalizedValue === "object") { - if (currentDepth == maxDepth) { - return undefined; - } + // Only the objects on the current path are tracked, so a value referenced more than once is kept unless it contains itself. + const pathEntries: object[] = []; + try { + if (typeof value === "object") { + if (ancestors.has(value)) { + return undefined; + } - if (Array.isArray(normalizedValue)) { - // Treat an object inside of an array as a single level - const depth: number = parentIsArray ? currentDepth + 1 : currentDepth; - return normalizedValue.map((e) => pruneImpl(e, maxDepth, depth, seen, true)); + ancestors.add(value); + pathEntries.push(value); } - if (normalizedValue instanceof Date) { - return normalizedValue; + if (isUnsupportedType(value)) { + return undefined; } - // Check for circular references - if (Object.prototype.toString.call(normalizedValue) === "[object Object]") { - if (seen.has(normalizedValue as object)) { + const normalizedValue = normalizeValue(value, currentDepth); + if (normalizedValue !== null && typeof normalizedValue === "object") { + if (currentDepth == maxDepth) { return undefined; } - seen.add(normalizedValue as object); - } + if (normalizedValue !== value) { + if (ancestors.has(normalizedValue)) { + return undefined; + } - const keys = new Set([...Object.getOwnPropertyNames(normalizedValue), ...Object.getOwnPropertySymbols(normalizedValue)]); - // Loop over and add any inherited prototype properties - for (const key in normalizedValue) { - keys.add(key); - } + ancestors.add(normalizedValue); + pathEntries.push(normalizedValue); + } + + if (Array.isArray(normalizedValue)) { + // Treat an object inside of an array as a single level + const depth: number = parentIsArray ? currentDepth + 1 : currentDepth; + return normalizedValue.map((e) => pruneImpl(e, maxDepth, depth, ancestors, true)); + } - type NonSymbolPropertyKey = Exclude; - const result: Record = {}; - for (const key of keys) { - // Normalize the key so Symbols are converted to strings. - const normalizedKey = normalizeValue(key) as NonSymbolPropertyKey; + if (normalizedValue instanceof Date) { + return normalizedValue; + } + + const keys = new Set([...Object.getOwnPropertyNames(normalizedValue), ...Object.getOwnPropertySymbols(normalizedValue)]); + // Loop over and add any inherited prototype properties + for (const key in normalizedValue) { + keys.add(key); + } + + type NonSymbolPropertyKey = Exclude; + const result: Record = {}; + for (const key of keys) { + // Normalize the key so Symbols are converted to strings. + const normalizedKey = normalizeValue(key, currentDepth) as NonSymbolPropertyKey; + + let objectValue: unknown; + try { + objectValue = (normalizedValue as { [index: PropertyKey]: unknown })[key]; + } catch { + // Drop properties whose getter throws. + result[normalizedKey] = undefined; + continue; + } + + result[normalizedKey] = pruneImpl(objectValue, maxDepth, currentDepth + 1, ancestors); + } - const objectValue = (normalizedValue as { [index: PropertyKey]: unknown })[key]; - result[normalizedKey] = pruneImpl(objectValue, maxDepth, currentDepth + 1, seen); + return result; } - return result; + return normalizedValue; + } catch { + // Drop values that cannot be read, such as a throwing toJSON or a revoked Proxy. + return undefined; + } finally { + for (const entry of pathEntries) { + ancestors.delete(entry); + } } - - return normalizedValue; } if (depth < 0) { diff --git a/packages/core/src/plugins/EventPluginManager.ts b/packages/core/src/plugins/EventPluginManager.ts index 3f50605b..5af62566 100644 --- a/packages/core/src/plugins/EventPluginManager.ts +++ b/packages/core/src/plugins/EventPluginManager.ts @@ -18,7 +18,7 @@ export class EventPluginManager { try { await plugin.startup(context); } catch (ex) { - context.log.error(`Error running plugin startup"${plugin.name}": ${ex instanceof Error ? ex.message : ex + ""}`); + context.log.error(`Error running plugin startup "${plugin.name}": ${getErrorMessage(ex)}`); } } } @@ -32,7 +32,7 @@ export class EventPluginManager { try { await plugin.suspend(context); } catch (ex) { - context.log.error(`Error running plugin suspend"${plugin.name}": ${ex instanceof Error ? ex.message : ex + ""}`); + context.log.error(`Error running plugin suspend "${plugin.name}": ${getErrorMessage(ex)}`); } } } @@ -50,8 +50,8 @@ export class EventPluginManager { try { await plugin.run(context); } catch (ex) { - context.cancelled = true; - context.log.error(`Error running plugin "${plugin.name}": ${ex instanceof Error ? ex.message : ex + ""}. Discarding Event.`); + // A failing plugin must not drop the event; only an explicit context.cancelled does. + context.log.error(`Error running plugin "${plugin.name}": ${getErrorMessage(ex)}. Continuing with the event.`); } } } @@ -65,3 +65,7 @@ export class EventPluginManager { config.addPlugin(new SubmissionMethodPlugin()); } } + +function getErrorMessage(ex: unknown): string { + return ex instanceof Error ? ex.message : ex + ""; +} diff --git a/packages/core/src/plugins/default/DuplicateCheckerPlugin.ts b/packages/core/src/plugins/default/DuplicateCheckerPlugin.ts index bd04a429..5237f8f5 100644 --- a/packages/core/src/plugins/default/DuplicateCheckerPlugin.ts +++ b/packages/core/src/plugins/default/DuplicateCheckerPlugin.ts @@ -1,4 +1,4 @@ -import { InnerErrorInfo } from "../../models/data/ErrorInfo.js"; +import { InnerErrorInfo, SimpleError } from "../../models/data/ErrorInfo.js"; import { KnownEventDataKeys } from "../../models/Event.js"; import { allowProcessToExitWithoutWaitingForTimerOrInterval, getHashCode } from "../../Utils.js"; import { EventPluginContext } from "../../plugins/EventPluginContext.js"; @@ -33,7 +33,7 @@ export class DuplicateCheckerPlugin implements IEventPlugin { } public run(context: EventPluginContext): Promise { - function calculateHashCode(error: InnerErrorInfo | undefined): number { + function calculateHashCode(error: InnerErrorInfo | SimpleError | undefined): number { let hash = 0; while (error) { if (error.message && error.message.length) { @@ -49,7 +49,7 @@ export class DuplicateCheckerPlugin implements IEventPlugin { return hash; } - const error = context.event.data?.[KnownEventDataKeys.Error]; + const error = context.event.data?.[KnownEventDataKeys.Error] ?? context.event.data?.[KnownEventDataKeys.SimpleError]; const hashCode = calculateHashCode(error); if (hashCode) { const count = context.event.count || 1; diff --git a/packages/core/src/plugins/default/EventExclusionPlugin.ts b/packages/core/src/plugins/default/EventExclusionPlugin.ts index 2ef4decb..ecb17f81 100644 --- a/packages/core/src/plugins/default/EventExclusionPlugin.ts +++ b/packages/core/src/plugins/default/EventExclusionPlugin.ts @@ -1,3 +1,4 @@ +import { InnerErrorInfo, SimpleError } from "../../models/data/ErrorInfo.js"; import { KnownEventDataKeys, LogLevel } from "../../models/Event.js"; import { isMatch, startsWith, toBoolean } from "../../Utils.js"; import { EventPluginContext } from "../../plugins/EventPluginContext.js"; @@ -16,12 +17,13 @@ export class EventExclusionPlugin implements IEventPlugin { const minLogLevel = this.getMinLogLevel(settings, ev.source); const logLevel = this.getLogLevel(ev.data && ev.data[KnownEventDataKeys.Level]); - if (logLevel !== -1 && (logLevel === 6 || logLevel < minLogLevel)) { + // A log without a recognized level is only excluded when logging is turned off for its source. + if (logLevel === -1 ? minLogLevel === 6 : logLevel === 6 || logLevel < minLogLevel) { log.info("Cancelling log event due to minimum log level."); context.cancelled = true; } } else if (ev.type === "error") { - let error = ev.data && ev.data[KnownEventDataKeys.Error]; + let error: InnerErrorInfo | SimpleError | undefined = ev.data?.[KnownEventDataKeys.Error] ?? ev.data?.[KnownEventDataKeys.SimpleError]; while (!context.cancelled && error) { if (this.getTypeAndSourceSetting(settings, ev.type, error.type, true) === false) { log.info(`Cancelling error from excluded exception type: ${error.type}`); diff --git a/packages/core/test/Utils.test.ts b/packages/core/test/Utils.test.ts index 70c8bc44..89424929 100644 --- a/packages/core/test/Utils.test.ts +++ b/packages/core/test/Utils.test.ts @@ -1,6 +1,19 @@ import { describe, expect, test, vi } from "vitest"; -import { endsWith, guid, isEmpty, isMatch, parseVersion, prune, randomNumber, startsWith, stringify, toBoolean } from "../src/Utils.js"; +import { + endsWith, + getCookies, + guid, + isEmpty, + isMatch, + parseQueryString, + parseVersion, + prune, + randomNumber, + startsWith, + stringify, + toBoolean +} from "../src/Utils.js"; describe("Utils", () => { function getObjectWithInheritedProperties(): unknown { @@ -52,7 +65,7 @@ describe("Utils", () => { expect(actual).toStrictEqual(expected); }); - test("array reference removes duplicated object references", () => { + test("array reference keeps shared object references", () => { type PropertyObject = { property: string }; const propObject: PropertyObject = { property: "string" @@ -62,12 +75,160 @@ describe("Utils", () => { { property: "string" }, - undefined + { + property: "string" + } ]; const actual = prune([propObject, propObject]); expect(actual).toStrictEqual(expected); }); + test("should keep shared object references that are not circular", () => { + const shared = { + property: "string" + }; + expect( + prune({ + a: shared, + b: shared, + list: [shared] + }) + ).toStrictEqual({ + a: { + property: "string" + }, + b: { + property: "string" + }, + list: [ + { + property: "string" + } + ] + }); + }); + + test("should prune arrays that contain themselves", () => { + const list: unknown[] = ["string"]; + list.push(list); + expect(prune(list)).toStrictEqual(["string", undefined]); + }); + + test("should prune errors that reference themselves", () => { + const error = new Error("error") as Error & { self?: Error; nested?: { error: Error } }; + error.self = error; + error.nested = { + error + }; + + expect(prune(error, 3)).toStrictEqual({ + stack: error.stack, + message: "error", + self: undefined, + nested: { + error: undefined + } + }); + }); + + test("should drop a property whose getter throws and keep the rest", () => { + const value = { + name: "value", + get broken(): string { + throw new Error("getter failed"); + }, + nested: { + ok: true + } + }; + + expect(prune(value)).toStrictEqual({ + name: "value", + broken: undefined, + nested: { + ok: true + } + }); + }); + + test("should drop a value whose toJSON throws and keep the rest", () => { + const value = { + name: "value", + broken: { + toJSON(): unknown { + throw new Error("toJSON failed"); + } + } + }; + + expect(prune(value)).toStrictEqual({ + name: "value", + broken: undefined + }); + }); + + test("should drop a revoked proxy and keep the rest", () => { + const { proxy, revoke } = Proxy.revocable( + { + secret: "value" + }, + {} + ); + revoke(); + + expect( + prune({ + name: "value", + proxy, + list: [proxy] + }) + ).toStrictEqual({ + name: "value", + proxy: undefined, + list: [undefined] + }); + }); + + test("should stop toJSON chains that never end", () => { + const self = { + name: "self", + toJSON(): unknown { + return self; + } + }; + + let calls = 0; + const createChain = (): unknown => ({ + toJSON(): unknown { + calls++; + return createChain(); + } + }); + + expect( + prune({ + name: "value", + self + }) + ).toStrictEqual({ + name: "value", + self: undefined + }); + expect( + prune( + { + name: "value", + chain: createChain() + }, + 5 + ) + ).toStrictEqual({ + name: "value", + chain: undefined + }); + expect(calls).toBeLessThanOrEqual(5); + }); + test("array cloned no object references", () => { const expected = [ { @@ -997,6 +1158,109 @@ describe("Utils", () => { }); }); + describe("stringify unsafe values", () => { + test("should serialize an error with a throwing getter", () => { + const error = new Error("error"); + Object.defineProperty(error, "details", { + enumerable: true, + get(): string { + throw new Error("getter failed"); + } + }); + + expect(stringify(error, ["stack"])).toBe( + JSON.stringify({ + message: "error" + }) + ); + }); + + test("should serialize a revoked proxy as undefined", () => { + const { proxy, revoke } = Proxy.revocable({}, {}); + revoke(); + + expect( + stringify({ + proxy, + name: "value" + }) + ).toBe( + JSON.stringify({ + name: "value" + }) + ); + }); + }); + + describe("parseQueryString", () => { + test("should decode keys and values", () => { + expect(parseQueryString("first%20name=Blake%20N&empty=")).toStrictEqual({ + "first name": "Blake N", + empty: "" + }); + }); + + test("should keep malformed percent encoding instead of throwing", () => { + expect(parseQueryString("discount=100%&code=%E0%A4%A&ok=yes")).toStrictEqual({ + discount: "100%", + code: "%E0%A4%A", + ok: "yes" + }); + }); + + test("should only split on the first equals sign", () => { + expect(parseQueryString("token=abc==&expr=a=b")).toStrictEqual({ + token: "abc==", + expr: "a=b" + }); + }); + + test("should use an empty string for a key without a value", () => { + expect(parseQueryString("flag&other=1")).toStrictEqual({ + flag: "", + other: "1" + }); + }); + + test("should skip empty keys", () => { + expect(parseQueryString("&=value&a=1&&")).toStrictEqual({ + a: "1" + }); + }); + + test("should match exclusions against the decoded key", () => { + expect(parseQueryString("pass%77ord=secret&user=blake", ["password"])).toStrictEqual({ + user: "blake" + }); + }); + }); + + describe("getCookies", () => { + test("should keep equals signs in cookie values", () => { + expect(getCookies("session=abc123==; theme=dark")).toStrictEqual({ + session: "abc123==", + theme: "dark" + }); + }); + + test("should decode cookie values and keep malformed encoding", () => { + expect(getCookies("name=Blake%20N; discount=100%")).toStrictEqual({ + name: "Blake N", + discount: "100%" + }); + }); + + test("should match exclusions against the decoded name", () => { + expect(getCookies("pass%77ord=secret; user=blake", ["password"])).toStrictEqual({ + user: "blake" + }); + }); + + test("should return null when there are no cookies", () => { + expect(getCookies("")).toBeNull(); + }); + }); + test("should parse version from url", () => { expect(parseVersion("https://code.jquery.com/jquery-2.1.3.js")).toBe("2.1.3"); expect(parseVersion("//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css")).toBe("3.3.4"); diff --git a/packages/core/test/plugins/EventPluginManager.test.ts b/packages/core/test/plugins/EventPluginManager.test.ts index 57083e44..a598d7b0 100644 --- a/packages/core/test/plugins/EventPluginManager.test.ts +++ b/packages/core/test/plugins/EventPluginManager.test.ts @@ -1,9 +1,11 @@ -import { describe, expect, test } from "vitest"; +import { describe, expect, Mock, test, vi } from "vitest"; import { EventContext } from "../../src/models/EventContext.js"; import { ExceptionlessClient } from "../../src/ExceptionlessClient.js"; import { EventPluginContext } from "../../src/plugins/EventPluginContext.js"; import { EventPluginManager } from "../../src/plugins/EventPluginManager.js"; +import { PluginContext } from "../../src/plugins/PluginContext.js"; +import { ILog } from "../../src/logging/ILog.js"; import { delay } from "../helpers.js"; describe("EventPluginManager", () => { @@ -59,40 +61,71 @@ describe("EventPluginManager", () => { expect(context.cancelled).toBe(true); }); - test("throwing error should stop plugin execution.", async () => { + function createClient(): { client: ExceptionlessClient; logError: Mock<(message: string) => void> } { const client = new ExceptionlessClient(); client.config.apiKey = "UNIT_TEST_API_KEY"; - const context = new EventPluginContext(client, {}, new EventContext()); + const logError = vi.fn<(message: string) => void>(); + const log: ILog = { + trace: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + error: logError + }; + client.config.services.log = log; - expect(client.config.plugins).not.toBeNull(); while (client.config.plugins.length > 0) { client.config.removePlugin(client.config.plugins[0]); } + return { + client, + logError + }; + } + + test("throwing error should log and continue with the event.", async () => { + const { client, logError } = createClient(); + const context = new EventPluginContext(client, {}, new EventContext()); + client.config.addPlugin("1", 1, () => { throw new Error("Random Error"); }); - client.config.addPlugin("2", 2, () => { - throw new Error("Plugin should not be called due to cancellation"); + client.config.addPlugin("2", 2, async (ctx: EventPluginContext) => { + await delay(25); + ctx.event.source = "plugin 2"; }); await EventPluginManager.run(context); - expect(context.cancelled).toBe(true); + expect(context.cancelled).toBe(false); + expect(context.event.source).toBe("plugin 2"); + expect(logError).toHaveBeenCalledWith(expect.stringContaining('"1"')); + expect(logError).toHaveBeenCalledWith(expect.stringContaining("Random Error")); }); - test("should cancel via timeout.", async () => { - const client = new ExceptionlessClient(); - client.config.apiKey = "UNIT_TEST_API_KEY"; + test("rejected promise should log and continue with the event.", async () => { + const { client, logError } = createClient(); const context = new EventPluginContext(client, {}, new EventContext()); - expect(client.config.plugins).not.toBeNull(); - while (client.config.plugins.length > 0) { - client.config.removePlugin(client.config.plugins[0]); - } + client.config.addPlugin("1", 1, () => Promise.reject(new Error("Async Error"))); + client.config.addPlugin("2", 2, (ctx: EventPluginContext) => { + ctx.event.source = "plugin 2"; + return Promise.resolve(); + }); - client.config.addPlugin("1", 1, async () => { - await delay(25); + await EventPluginManager.run(context); + expect(context.cancelled).toBe(false); + expect(context.event.source).toBe("plugin 2"); + expect(logError).toHaveBeenCalledWith(expect.stringContaining("Async Error")); + }); + + test("plugin that cancels before throwing should keep the event cancelled.", async () => { + const { client } = createClient(); + const context = new EventPluginContext(client, {}, new EventContext()); + + client.config.addPlugin("1", 1, (ctx: EventPluginContext) => { + ctx.cancelled = true; + throw new Error("Random Error"); }); client.config.addPlugin("2", 2, () => { @@ -103,6 +136,42 @@ describe("EventPluginManager", () => { expect(context.cancelled).toBe(true); }); + test("failing startup and suspend should log and run the remaining plugins.", async () => { + const { client, logError } = createClient(); + const calls: string[] = []; + + client.config.addPlugin({ + name: "failing", + priority: 1, + startup: () => Promise.reject(new Error("Startup Error")), + suspend: () => { + throw new Error("Suspend Error"); + } + }); + + client.config.addPlugin({ + name: "working", + priority: 2, + startup: () => { + calls.push("startup"); + return Promise.resolve(); + }, + suspend: () => { + calls.push("suspend"); + return Promise.resolve(); + } + }); + + const context = new PluginContext(client); + await EventPluginManager.startup(context); + await EventPluginManager.suspend(context); + + expect(calls).toStrictEqual(["startup", "suspend"]); + expect(logError).toHaveBeenCalledWith(expect.stringContaining('"failing"')); + expect(logError).toHaveBeenCalledWith(expect.stringContaining("Startup Error")); + expect(logError).toHaveBeenCalledWith(expect.stringContaining("Suspend Error")); + }); + test("should ensure config plugins are not wrapped.", async () => { const client = new ExceptionlessClient(); client.config.apiKey = "UNIT_TEST_API_KEY"; diff --git a/packages/core/test/plugins/default/DuplicateCheckerPlugin.test.ts b/packages/core/test/plugins/default/DuplicateCheckerPlugin.test.ts index ad758afc..953f340a 100644 --- a/packages/core/test/plugins/default/DuplicateCheckerPlugin.test.ts +++ b/packages/core/test/plugins/default/DuplicateCheckerPlugin.test.ts @@ -96,6 +96,42 @@ describe("DuplicateCheckerPlugin", () => { expect(contextOfSecondRun.cancelled).not.toBe(true); }); + const runSimple = async (message: string, stackTrace: string): Promise => { + const context = new EventPluginContext( + client, + { + type: "error", + data: { + "@simple_error": { + type: "TypeError", + message, + stack_trace: stackTrace + } + } + }, + new EventContext() + ); + + await plugin.run(context); + return context; + }; + + test("should ignore duplicate simple error within window", async () => { + const stack = "TypeError: This is a test\n at createException (index.js:1:50)"; + const contextOfFirstRun = await runSimple("This is a test", stack); + expect(contextOfFirstRun.cancelled).toBe(false); + + const contextOfSecondRun = await runSimple("This is a test", stack); + expect(contextOfSecondRun.cancelled).toBe(true); + }); + + test("shouldn't ignore different simple error within window", async () => { + await runSimple("This is a test", "TypeError: This is a test\n at createException (index.js:1:50)"); + const contextOfSecondRun = await runSimple("This is a test", "TypeError: This is a test\n at createException2 (index.js:1:50)"); + + expect(contextOfSecondRun.cancelled).toBe(false); + }); + test("shouldn't ignore duplicate after window", async () => { await run(Exception1StackTrace); diff --git a/packages/core/test/plugins/default/EventExclusionPlugin.test.ts b/packages/core/test/plugins/default/EventExclusionPlugin.test.ts index 39bda149..cb153e99 100644 --- a/packages/core/test/plugins/default/EventExclusionPlugin.test.ts +++ b/packages/core/test/plugins/default/EventExclusionPlugin.test.ts @@ -56,6 +56,12 @@ describe("EventExclusionPlugin", () => { test("[info] Test (source min level: debug)", async () => expect(await run("Test", "info", "@@log:Test", "debug")).toBe(false)); test("[trace] Test (global min level: debug)", async () => expect(await run("Test", "trace", "@@log:*", "debug")).toBe(true)); test("[warn] Test (global min level: debug)", async () => expect(await run("Test", "warn", "@@log:*", "debug")).toBe(false)); + test(" (global min level: Off)", async () => expect(await run(undefined, null, "@@log:*", "Off")).toBe(true)); + test("Test (global min level: Off)", async () => expect(await run("Test", null, "@@log:*", "Off")).toBe(true)); + test("Test (source min level: Off)", async () => expect(await run("Test", null, "@@log:Test", "Off")).toBe(true)); + test("Test (source min level: false)", async () => expect(await run("Test", null, "@@log:Test", "false")).toBe(true)); + test("Other (source min level: Off)", async () => expect(await run("Other", null, "@@log:Test", "Off")).toBe(false)); + test("Test (global min level: fatal)", async () => expect(await run("Test", null, "@@log:*", "fatal")).toBe(false)); }); describe("should exclude log levels with info default", () => { @@ -207,7 +213,32 @@ describe("EventExclusionPlugin", () => { test("404= off", async () => expect(await run("404", "", "@@404:", "false")).toBe(true)); }); - describe("should exclude exception type", () => { + describe.each([ + { + key: KnownEventDataKeys.Error, + error: { + type: "ReferenceError", + message: "This is a test", + stack_trace: [], + inner: { + type: "TypeError", + message: "Inner" + } + } + }, + { + key: KnownEventDataKeys.SimpleError, + error: { + type: "ReferenceError", + message: "This is a test", + stack_trace: "", + inner: { + type: "TypeError", + message: "Inner" + } + } + } + ])("should exclude exception type from $key", ({ key, error }) => { const run = async (settingKey: string | null | undefined): Promise => { const client = new ExceptionlessClient(); @@ -220,11 +251,7 @@ describe("EventExclusionPlugin", () => { { type: "error", data: { - "@error": { - type: "ReferenceError", - message: "This is a test", - stack_trace: [] - } + [key]: error } }, new EventContext() @@ -240,5 +267,6 @@ describe("EventExclusionPlugin", () => { test("@@error:ReferenceError", async () => expect(await run("@@error:ReferenceError")).toBe(true)); test("@@error:*Error", async () => expect(await run("@@error:*Error")).toBe(true)); test("@@error:*", async () => expect(await run("@@error:*")).toBe(true)); + test("@@error:TypeError (inner)", async () => expect(await run("@@error:TypeError")).toBe(true)); }); }); From 4cbe94417de31e8ba4b89c8793e9b9b72ec08dd2 Mon Sep 17 00:00:00 2001 From: "Eric J. Smith" Date: Tue, 1 Dec 2026 19:15:42 -0600 Subject: [PATCH 2/2] Keep healthy data when an array element, Date, or thrown value misbehaves - Read array elements one at a time so a throwing index getter drops only that element. - Serialize a Date with an overridden toJSON inside prune, where a throw drops only that value. - Format plugin errors without throwing (a thrown Symbol made the catch handler itself throw). --- packages/core/src/Utils.ts | 24 +++++++++++- .../core/src/plugins/EventPluginManager.ts | 7 +++- packages/core/test/Utils.test.ts | 38 +++++++++++++++++++ .../test/plugins/EventPluginManager.test.ts | 19 ++++++++++ 4 files changed, 85 insertions(+), 3 deletions(-) diff --git a/packages/core/src/Utils.ts b/packages/core/src/Utils.ts index 2456f645..f1693185 100644 --- a/packages/core/src/Utils.ts +++ b/packages/core/src/Utils.ts @@ -484,11 +484,31 @@ export function prune(value: unknown, depth: number = 10): unknown { if (Array.isArray(normalizedValue)) { // Treat an object inside of an array as a single level const depth: number = parentIsArray ? currentDepth + 1 : currentDepth; - return normalizedValue.map((e) => pruneImpl(e, maxDepth, depth, ancestors, true)); + // Read each element separately so a throwing index getter only drops that element. + const array = normalizedValue as unknown[]; + const result: unknown[] = []; + for (let index = 0; index < array.length; index++) { + let element: unknown; + try { + element = array[index]; + } catch { + result[index] = undefined; + continue; + } + + result[index] = pruneImpl(element, maxDepth, depth, ancestors, true); + } + + return result; } if (normalizedValue instanceof Date) { - return normalizedValue; + if (normalizedValue.toJSON === Date.prototype.toJSON && normalizedValue.toISOString === Date.prototype.toISOString) { + return normalizedValue; + } + + // A Date with an overridden toJSON is serialized here, where a throw only drops this value. + return normalizedValue.toJSON(); } const keys = new Set([...Object.getOwnPropertyNames(normalizedValue), ...Object.getOwnPropertySymbols(normalizedValue)]); diff --git a/packages/core/src/plugins/EventPluginManager.ts b/packages/core/src/plugins/EventPluginManager.ts index 5af62566..b232becc 100644 --- a/packages/core/src/plugins/EventPluginManager.ts +++ b/packages/core/src/plugins/EventPluginManager.ts @@ -67,5 +67,10 @@ export class EventPluginManager { } function getErrorMessage(ex: unknown): string { - return ex instanceof Error ? ex.message : ex + ""; + // Formatting must never throw (for example a thrown Symbol, or a revoked Proxy), or the event would still be lost. + try { + return ex instanceof Error ? String(ex.message) : String(ex); + } catch { + return "Unknown error"; + } } diff --git a/packages/core/test/Utils.test.ts b/packages/core/test/Utils.test.ts index 89424929..3db2e1ef 100644 --- a/packages/core/test/Utils.test.ts +++ b/packages/core/test/Utils.test.ts @@ -1175,6 +1175,44 @@ describe("Utils", () => { ); }); + test("should keep healthy array elements when one index getter throws", () => { + const array = [1, 2, 3]; + Object.defineProperty(array, 1, { + enumerable: true, + get(): number { + throw new Error("getter failed"); + } + }); + + expect( + stringify({ + array + }) + ).toBe( + JSON.stringify({ + array: [1, null, 3] + }) + ); + }); + + test("should drop a date whose toJSON throws", () => { + const date = new Date(0); + date.toJSON = () => { + throw new Error("toJSON failed"); + }; + + expect( + stringify({ + ok: true, + date + }) + ).toBe( + JSON.stringify({ + ok: true + }) + ); + }); + test("should serialize a revoked proxy as undefined", () => { const { proxy, revoke } = Proxy.revocable({}, {}); revoke(); diff --git a/packages/core/test/plugins/EventPluginManager.test.ts b/packages/core/test/plugins/EventPluginManager.test.ts index a598d7b0..26439b8f 100644 --- a/packages/core/test/plugins/EventPluginManager.test.ts +++ b/packages/core/test/plugins/EventPluginManager.test.ts @@ -119,6 +119,25 @@ describe("EventPluginManager", () => { expect(logError).toHaveBeenCalledWith(expect.stringContaining("Async Error")); }); + test("throwing a symbol should log and continue with the event.", async () => { + const { client, logError } = createClient(); + const context = new EventPluginContext(client, {}, new EventContext()); + + client.config.addPlugin("1", 1, () => { + // eslint-disable-next-line @typescript-eslint/only-throw-error + throw Symbol("failure"); + }); + client.config.addPlugin("2", 2, (ctx: EventPluginContext) => { + ctx.event.source = "plugin 2"; + return Promise.resolve(); + }); + + await EventPluginManager.run(context); + expect(context.cancelled).toBe(false); + expect(context.event.source).toBe("plugin 2"); + expect(logError).toHaveBeenCalledWith(expect.stringContaining("Symbol(failure)")); + }); + test("plugin that cancels before throwing should keep the event cancelled.", async () => { const { client } = createClient(); const context = new EventPluginContext(client, {}, new EventContext());