Skip to content

Build your personal knowledge base with Trilium Notes

fix(client): log each uncaught error once, without the editor object

Elian Doranb0156c533b69
diff --git a/apps/client/src/services/glob.spec.ts b/apps/client/src/services/glob.spec.ts
index 955a640fb6..f68c582898 100644
--- a/apps/client/src/services/glob.spec.ts
+++ b/apps/client/src/services/glob.spec.ts
@@ -120,19 +120,32 @@ describe("setupGlobs", () => {
});
});
+/** A `CKEditorError` as `ckeditor5` builds it: `context` holds an editor object, `data` the details. */
+function ckEditorError() {
+ const error = new Error("unexpected-error") as Error & Record<string, unknown>;
+ error.is = (type: string) => type === "CKEditorError";
+ error.context = { document: { roots: [ "main" ] } };
+ error.data = { originalError: "Editor crashed." };
+ return error;
+}
+
describe("window.onerror handler", () => {
beforeEach(() => glob.setupGlobs());
- it("logs full details for a normal error and serializes the error object", () => {
- const result = window.onerror!("Some failure", "http://x/app.js", 12, 34, new Error("boom"));
+ it("logs the message, then the stack without its header line", () => {
+ const error = new Error("boom");
+ error.stack = "Error: boom\n at run (app.js:1:2)";
+ const result = window.onerror!("Some failure", "http://x/app.js", 12, 34, error);
expect(result).toBe(false);
- expect((ws as any).logError).toHaveBeenCalledTimes(1);
- const msg = (ws as any).logError.mock.calls[0][0] as string;
- expect(msg).toContain("Message: Some failure");
- expect(msg).toContain("URL: http://x/app.js");
- expect(msg).toContain("Line: 12");
- expect(msg).toContain("Column: 34");
+ expect((ws as any).logError).toHaveBeenCalledExactlyOnceWith(
+ "Uncaught error: Some failure\n at run (app.js:1:2)");
+ });
+
+ it("logs where the error happened when it has no stack", () => {
+ window.onerror!("Some failure", "http://x/app.js", 12, 34, undefined);
+ expect((ws as any).logError).toHaveBeenCalledExactlyOnceWith(
+ "Uncaught error: Some failure\nat http://x/app.js:12:34");
});
it("reports no details for a generic 'Script error'", () => {
@@ -152,7 +165,18 @@ describe("window.onerror handler", () => {
window.onerror!("circular failure", "u", 1, 2, err);
const msg = (ws as any).logError.mock.calls[0][0] as string;
// The catch branch stringified the thrown serialization error via toString().
- expect(msg).toContain("Error object: Error: nope");
+ expect(msg).toContain("Details: Error: nope");
+ });
+
+ it("logs the details of a CKEditor error without its editor object", () => {
+ const error = ckEditorError();
+ error.stack = " at change (ckeditor5.js:1:2)";
+ window.onerror!("unexpected-error", "u", 1, 2, error);
+ expect((ws as any).logError).toHaveBeenCalledExactlyOnceWith([
+ "Uncaught error: unexpected-error",
+ "Details: {\"data\":{\"originalError\":\"Editor crashed.\"}}",
+ " at change (ckeditor5.js:1:2)"
+ ].join("\n"));
});
});
@@ -167,10 +191,11 @@ describe("unhandledrejection handler", () => {
it("logs full details for a normal rejection", () => {
dispatchRejection({ message: "rejected", lineNumber: 5, columnNumber: 6, stack: "stack" });
- const msg = (ws as any).logError.mock.calls[0][0] as string;
- expect(msg).toContain("Message: rejected");
- expect(msg).toContain("Line: 5");
- expect(msg).toContain("Column: 6");
+ expect((ws as any).logError.mock.calls[0][0]).toBe([
+ "Uncaught error: rejected",
+ "Details: {\"lineNumber\":5,\"columnNumber\":6}",
+ "stack"
+ ].join("\n"));
});
it("reports no details for a script error rejection", () => {
@@ -188,7 +213,19 @@ describe("unhandledrejection handler", () => {
// no .message -> string is undefined -> falls into the details branch
dispatchRejection(circular);
const msg = (ws as any).logError.mock.calls[0][0] as string;
- expect(msg).toContain("Error object: Error: bad");
+ expect(msg).toContain("Details: Error: bad");
+ });
+
+ it("logs a rejection with a value that is not an error", () => {
+ dispatchRejection("plain reason");
+ expect((ws as any).logError.mock.calls[0][0]).toBe("Uncaught error: plain reason");
+ });
+
+ it("leaves the editor object out of a CKEditor error", () => {
+ dispatchRejection(ckEditorError());
+ const msg = (ws as any).logError.mock.calls[0][0] as string;
+ expect(msg).toContain("Editor crashed.");
+ expect(msg).not.toContain("roots");
});
});
diff --git a/apps/client/src/services/glob.ts b/apps/client/src/services/glob.ts
index 85f149fb6a..de9b8c87e4 100644
--- a/apps/client/src/services/glob.ts
+++ b/apps/client/src/services/glob.ts
@@ -22,52 +22,16 @@ function setupGlobs() {
window.glob.treeCache = froca; // compatibility for CKEditor builds for a while
window.onerror = function (msg, url, lineNo, columnNo, error) {
- const string = String(msg).toLowerCase();
-
- let errorObjectString = "";
- try {
- errorObjectString = JSON.stringify(error);
- } catch (e: any) {
- errorObjectString = e.toString();
- }
- let message = "Uncaught error: ";
-
- if (string.includes("script error")) {
- message += "No details available";
- } else {
- message += [`Message: ${msg}`, `URL: ${url}`, `Line: ${lineNo}`, `Column: ${columnNo}`, `Error object: ${errorObjectString}`, `Stack: ${error && error.stack}`].join(", ");
- }
-
- ws.logError(message);
+ ws.logError(formatUncaughtError(String(msg), error, `${url}:${lineNo}:${columnNo}`));
return false;
};
window.addEventListener("unhandledrejection", (e) => {
- const string = e?.reason?.message?.toLowerCase();
-
- let message = "Uncaught error: ";
- let errorObjectString;
-
- try {
- errorObjectString = JSON.stringify(e.reason)
- } catch (error: any) {
- errorObjectString = error.toString();
- }
-
- if (string?.includes("script error")) {
- message += "No details available";
- } else {
- message += [
- `Message: ${e.reason.message}`,
- `Line: ${e.reason.lineNumber}`,
- `Column: ${e.reason.columnNumber}`,
- `Error object: ${errorObjectString}`,
- `Stack: ${e.reason && e.reason.stack}`
- ].join(", ");
- }
-
- ws.logError(message);
+ const reason: unknown = e?.reason;
+ const message = (reason as { message?: unknown } | null)?.message;
+ ws.logError(formatUncaughtError(
+ typeof message === "string" ? message : String(reason), reason));
return false;
});
@@ -95,6 +59,70 @@ export async function requireCss(url: string, prependAssetPath = true) {
}
}
+/**
+ * The log entry of an uncaught error: the message, the error's other properties as JSON, then its
+ * stack, or `location` when it has none.
+ */
+function formatUncaughtError(message: string, error: unknown, location?: string) {
+ if (message.toLowerCase().includes("script error")) {
+ return "Uncaught error: No details available";
+ }
+
+ const lines = [ `Uncaught error: ${message}` ];
+ const details = serializeDetails(error);
+ if (details) {
+ lines.push(`Details: ${details}`);
+ }
+
+ const stack = stackWithoutHeader(error);
+ if (stack) {
+ lines.push(stack);
+ } else if (location) {
+ lines.push(`at ${location}`);
+ }
+
+ return lines.join("\n");
+}
+
+/**
+ * The JSON of an error's properties other than the `name`, `message` and `stack` the log entry
+ * already shows, or `undefined` when it has none. A `CKEditorError` carries the editor object that
+ * threw as its `context`, which would serialize the whole document, so it is left out.
+ */
+function serializeDetails(error: unknown) {
+ if (typeof error !== "object" || error === null) {
+ return undefined;
+ }
+
+ try {
+ const json = JSON.stringify(error, function (this: unknown, key, value) {
+ if (this === error && [ "name", "message", "stack" ].includes(key)) {
+ return undefined;
+ }
+ return key === "context" && isCKEditorError(this) ? undefined : value;
+ });
+ return json === "{}" ? undefined : json;
+ } catch (e) {
+ return String(e);
+ }
+}
+
+/** The stack of an error, without the `Name: message` line V8 starts it with. */
+function stackWithoutHeader(error: unknown) {
+ const { name, message, stack } = (error ?? {}) as { name?: unknown; message?: unknown; stack?: unknown };
+ if (typeof stack !== "string") {
+ return undefined;
+ }
+
+ const header = `${name}: ${message}`;
+ return (stack.startsWith(header) ? stack.slice(header.length) : stack).replace(/^\n+/, "");
+}
+
+function isCKEditorError(value: unknown) {
+ const is = (value as { is?: unknown } | null)?.is;
+ return typeof is === "function" && is.call(value, "CKEditorError") === true;
+}
+
export default {
setupGlobs
};
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts
index e3fa5ab789..de519c3ce2 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts
@@ -43,7 +43,7 @@ const {
} = await import("./EditableText");
describe("reportEditorError", () => {
- it("logs the error and shows a toast that opens its details", () => {
+ it("shows a toast that opens the details, leaving the log to the global handler", () => {
vi.clearAllMocks();
const logError = vi.fn();
vi.stubGlobal("logError", logError);
@@ -51,7 +51,7 @@ describe("reportEditorError", () => {
reportEditorError(error);
- expect(logError).toHaveBeenCalledExactlyOnceWith(expect.stringContaining("TypeError: boom"));
+ expect(logError).not.toHaveBeenCalled();
expect(showPersistent).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({
id: "editor-error",
title: "editable_text.editor_error_title",
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index 2c94aff46f..043b46c331 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -750,8 +750,9 @@ function useTemplates() {
}
/**
- * Logs an error that escaped the editor and tells the user about it in a toast, which opens the
- * error details for a bug report. The editor keeps running, so a later error replaces the toast.
+ * Tells the user about an error that escaped the editor in a toast, which opens the error details
+ * for a bug report. The editor keeps running, so a later error replaces the toast. The global error
+ * handlers in `glob.ts` log the error.
*
* Exported for testing.
*/
@@ -761,7 +762,6 @@ export function reportEditorError(error: CKEditorError) {
stack: error.stack,
date: new Date().toISOString()
}, null, 4);
- logError(`CKEditor error: ${details}`);
toast.showPersistent({
id: "editor-error",