From d94d3db4aa15d3d9e35943f6b7d812dbe92527c9 Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Mon, 18 Sep 2023 17:37:48 +0200 Subject: [PATCH] feat: improve default error visualization (#1780) Adds code frame to errors if possible: Screenshot 2023-09-15 at 11 33 46 Default error page in dev mode: Screenshot 2023-09-15 at 11 30 59 Default error page in prod mode: Screenshot 2023-09-15 at 11 31 23 --- .../__snapshots__/code_frame_test.ts.snap | 58 ++++++++ src/server/code_frame.ts | 127 +++++++++++++++++ src/server/code_frame_test.ts | 59 ++++++++ src/server/context.ts | 20 ++- src/server/default_error_page.ts | 58 -------- src/server/default_error_page.tsx | 134 ++++++++++++++++++ tests/error_test.ts | 6 +- 7 files changed, 395 insertions(+), 67 deletions(-) create mode 100644 src/server/__snapshots__/code_frame_test.ts.snap create mode 100644 src/server/code_frame.ts create mode 100644 src/server/code_frame_test.ts delete mode 100644 src/server/default_error_page.ts create mode 100644 src/server/default_error_page.tsx diff --git a/src/server/__snapshots__/code_frame_test.ts.snap b/src/server/__snapshots__/code_frame_test.ts.snap new file mode 100644 index 00000000..f123ffd0 --- /dev/null +++ b/src/server/__snapshots__/code_frame_test.ts.snap @@ -0,0 +1,58 @@ +export const snapshot = {}; + +snapshot[`createCodeFrame markers 1`] = ` +" + 1 | foo +> 2 | bar + | ^ + 3 | baz +" +`; + +snapshot[`createCodeFrame markers 2`] = ` +" +> 1 | foo + | ^ + 2 | bar + 3 | baz +" +`; + +snapshot[`createCodeFrame markers 3`] = ` +" + 1 | foo + 2 | bar +> 3 | baz + | ^ +" +`; + +snapshot[`createCodeFrame markers 4`] = ` +" + 7 | + 8 | +> 9 | bar + | ^ + 10 | + 11 | + 12 | bar +" +`; + +snapshot[`createCodeFrame with indentation 1`] = ` +" + 1 | foo +> 2 | bar + | ^ + 3 | baz +" +`; + +snapshot[`createCodeFrame with indentation 2`] = ` +" + 1 | foo +> 2 | bar + | ^ + 3 | baz +" +`; diff --git a/src/server/code_frame.ts b/src/server/code_frame.ts new file mode 100644 index 00000000..fcd69180 --- /dev/null +++ b/src/server/code_frame.ts @@ -0,0 +1,127 @@ +import { colors, fromFileUrl } from "./deps.ts"; + +function tabs2Spaces(str: string) { + return str.replace(/^\t+/, (tabs) => " ".repeat(tabs.length)); +} + +/** + * Generate an excerpt of the location in the source around the + * specified position. + */ +export function createCodeFrame( + text: string, + lineNum: number, + columnNum: number, +): string | undefined { + // Default settings + const before = 2; + const after = 3; + + const lines = text.split("\n"); + + // Check if specified range is valid + if (lines.length <= lineNum || lines[lineNum].length < columnNum) { + return; + } + + const start = Math.max(0, lineNum - before); + const end = Math.min(lines.length, lineNum + after + 1); + + // Maximum space needed for line numbering in the current range. + // Necessary when the amount of digits of the line numbering grows: + // 999 | asdf + // 1000 | asdjadfjsa + const maxLineNum = String(end).length; + const padding = " ".repeat(maxLineNum); + + // Normalize all indentation (=tabs) to use 2 spaces. We need to + // apply the difference to the marker position to move it back in + // place. + const spaceLines: string[] = []; + let maxLineLen = 0; + for (let i = start; i < end; i++) { + const line = tabs2Spaces(lines[i]); + spaceLines.push(line); + + if (line.length > maxLineLen) maxLineLen = line.length; + } + + const activeLine = spaceLines[lineNum - start]; + // Move marker into correct place by taking the amount of + // normalized tabs into account + const count = Math.max( + 0, + activeLine.length - lines[lineNum].length + columnNum, + ); + + const sep = colors.dim("|"); + let out = ""; + + for (let i = 0; i < spaceLines.length; i++) { + const line = spaceLines[i]; + const currentLine = colors.dim( + (padding + (i + start + 1)).slice(-maxLineNum), + ); + + // Line where the error occured + if (i === lineNum - start) { + out += colors.red(">") + + ` ${currentLine} ${sep} ${line}\n`; + + const columnMarker = colors.bold(colors.red("^")); + out += ` ${padding} ${sep} ${" ".repeat(count)}${columnMarker}\n`; + } else { + out += ` ${currentLine} ${sep} ${line}\n`; + } + } + + return out; +} + +const STACK_FRAME = /^\s*at\s+(?:(.*)\s+)?\((.*):(\d+):(\d+)\)$/; +export interface StackFrame { + fnName: string; + file: string; + line: number; + column: number; +} +export function getFirstUserFile(stack: string): StackFrame | undefined { + const lines = stack.split("\n"); + for (let i = 0; i < lines.length; i++) { + const match = lines[i].match(STACK_FRAME); + if (match && match) { + const fnName = match[1] ?? ""; + const file = match[2]; + const line = +match[3]; + const column = +match[4]; + + if (file.startsWith("file://")) { + return { + fnName, + file, + line, + column, + }; + } + } + } +} + +export async function getCodeFrame(error: Error) { + if (!error.stack) return; + + const file = getFirstUserFile(error.stack); + if (file) { + try { + const filePath = fromFileUrl(file.file); + const text = await Deno.readTextFile(filePath); + return createCodeFrame( + text, + file.line - 1, + file.column - 1, + ); + } catch { + // Ignore + } + } +} diff --git a/src/server/code_frame_test.ts b/src/server/code_frame_test.ts new file mode 100644 index 00000000..826de1e2 --- /dev/null +++ b/src/server/code_frame_test.ts @@ -0,0 +1,59 @@ +import { assertEquals } from "$std/testing/asserts.ts"; +import { assertSnapshot } from "$std/testing/snapshot.ts"; +import { createCodeFrame, getFirstUserFile } from "./code_frame.ts"; +import { colors } from "./deps.ts"; + +function testCodeFrame(text: string, line: number, column: number) { + const codeFrame = createCodeFrame(text, line, column); + if (codeFrame !== undefined) { + return "\n" + colors.stripColor(codeFrame); + } + return codeFrame; +} + +const FILE = `file://example.com/foo.js`; + +Deno.test("getFirstUserFile", () => { + let stack = `Some message + at asdf.foo (https://example.com/foo.js:8:20) + at asdf.foo (${FILE}:8:20) + `; + assertEquals(getFirstUserFile(stack), { + fnName: "asdf.foo", + file: FILE, + column: 20, + line: 8, + }); + + stack = `Some message + at asdf.foo (https://example.com/foo.js:8:20) + at (${FILE}:8:20) + `; + assertEquals(getFirstUserFile(stack), { + fnName: "", + file: FILE, + column: 20, + line: 8, + }); +}); + +Deno.test("createCodeFrame invalid ranges", () => { + assertEquals(createCodeFrame("", 2, 10), undefined); + assertEquals(createCodeFrame("asdf", 2, 10), undefined); + assertEquals(createCodeFrame("asdf", 1, 10), undefined); +}); + +Deno.test("createCodeFrame markers", async (t) => { + await assertSnapshot(t, testCodeFrame("foo\nbar\nbaz", 1, 2)); + await assertSnapshot(t, testCodeFrame("foo\nbar\nbaz", 0, 0)); + await assertSnapshot(t, testCodeFrame("foo\nbar\nbaz", 2, 2)); + await assertSnapshot( + t, + testCodeFrame("foo\n\n\n\n\n\n\n\nbar\n\n\nbar", 8, 0), + ); +}); + +Deno.test("createCodeFrame with indentation", async (t) => { + await assertSnapshot(t, testCodeFrame("foo\n bar\nbaz", 1, 6)); + await assertSnapshot(t, testCodeFrame("foo\n\t\tbar\nbaz", 1, 2)); +}); diff --git a/src/server/context.ts b/src/server/context.ts index 8eea5a18..2ba24ac4 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -20,7 +20,7 @@ import { setDevMode, } from "./constants.ts"; import { BUILD_ID, setBuildId } from "./build_id.ts"; -import DefaultErrorHandler from "./default_error_page.ts"; +import DefaultErrorHandler from "./default_error_page.tsx"; import { AppModule, BaseRoute, @@ -63,6 +63,7 @@ import { } from "../build/mod.ts"; import { InternalRoute } from "./router.ts"; import { setAllIslands } from "./rendering/preact_hooks.ts"; +import { getCodeFrame } from "./code_frame.ts"; const DEFAULT_CONN_INFO: ServeHandlerInfo = { localAddr: { transport: "tcp", hostname: "localhost", port: 8080 }, @@ -798,7 +799,6 @@ export class ServerContext { if (route.component === undefined) { throw new Error("This page does not have a component to render."); } - const layouts = selectSharedRoutes(route.baseRoute, this.#layouts); const resp = await internalRender({ @@ -898,7 +898,7 @@ export class ServerContext { this.#error, Status.InternalServerError, ); - const errorHandler: router.ErrorHandler = ( + const errorHandler: router.ErrorHandler = async ( req, ctx, error, @@ -906,8 +906,20 @@ export class ServerContext { console.error( "%cAn error occurred during route handling or page rendering.", "color:red", - error, ); + let codeFrame: string | undefined = undefined; + if (this.#dev && error instanceof Error) { + codeFrame = await getCodeFrame(error); + + if (codeFrame) { + console.error(); + console.error(codeFrame); + // deno-lint-ignore no-explicit-any + (error as any).codeFrame = codeFrame; + } + } + console.error(error); + return this.#error.handler( req, { diff --git a/src/server/default_error_page.ts b/src/server/default_error_page.ts deleted file mode 100644 index 43a62096..00000000 --- a/src/server/default_error_page.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { h } from "preact"; -import { DEBUG } from "./constants.ts"; -import type { ErrorPageProps } from "./types.ts"; - -export default function DefaultErrorPage(props: ErrorPageProps) { - const { error } = props; - - let message = undefined; - if (DEBUG) { - if (error instanceof Error) { - message = error.stack; - } else { - message = String(error); - } - } - - return h( - "div", - { - class: "frsh-error-page", - style: { - display: "flex", - justifyContent: "center", - alignItems: "center", - }, - }, - h( - "div", - { - style: { - border: "#f3f4f6 2px solid", - borderTop: "red 4px solid", - background: "#f9fafb", - margin: 16, - minWidth: "300px", - }, - }, - h("p", { - style: { - margin: 0, - fontSize: "12pt", - padding: 16, - fontFamily: "sans-serif", - }, - }, "An error occurred during route handling or page rendering."), - message && h("pre", { - style: { - margin: 0, - fontSize: "12pt", - overflowY: "auto", - padding: 16, - paddingTop: 0, - fontFamily: "monospace", - }, - }, message), - ), - ); -} diff --git a/src/server/default_error_page.tsx b/src/server/default_error_page.tsx new file mode 100644 index 00000000..967ec211 --- /dev/null +++ b/src/server/default_error_page.tsx @@ -0,0 +1,134 @@ +import { ComponentChildren, h } from "preact"; +import { DEBUG } from "./constants.ts"; +import type { ErrorPageProps, RouteConfig } from "./types.ts"; +import { colors } from "$fresh/src/server/deps.ts"; + +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +// Just to get some syntax highlighting +const css = (arr: TemplateStringsArray, ...exts: never[]) => { + if (exts.length) throw new Error("Not allowed"); + return arr[0]; +}; + +const errorCss = css` + :root { + --bg: #fff; + --bg-code-frame: rgb(255, 0, 32, 0.1); + --bg-active-line: #fbcecc; + --text: #222; + --text2: #444; + --title: #e84644; + --code: #333; + font-family: sans-serif; + line-height: 1.4; + color: var(--text); + background: var(--bg); + } + + * { + box-sizing: border-box; + } + + @media (prefers-color-scheme: dark) { + :root { + --bg-code-frame: rgba(251, 93, 113, 0.2); + --bg-active-line: #4f1919; + --bg: #353535; + --text: #f7f7f7; + --text2: #ddd; + --code: #fdd1d1; + } + } + + .inner { + max-width: 48rem; + padding: 4rem 1rem; + margin: 0 auto; + } + + .title { + color: var(--title); + font-weight: normal; + font-size: 1.5rem; + } + + .code-frame { + overflow: auto; + padding: 0.5rem; + background: var(--bg-code-frame); + color: var(--code); + } + .line { + padding: 0.25rem 0.5rem; + } + .active-line { + display: inline-block; + width: 100%; + background: var(--bg-active-line); + } + + .stack { + overflow-x: auto; + } +`; + +export default function DefaultErrorPage( + props: ErrorPageProps, +) { + const { error } = props; + + let title = "An error occurred during route handling or page rendering."; + + let codeFrame; + let stack; + + if (DEBUG) { + if (error instanceof Error) { + title = error.message; + // deno-lint-ignore no-explicit-any + codeFrame = (error as any).codeFrame; + stack = error.stack ?? ""; + } else { + title = String(error); + } + } + + return ( +
+ +
+

{title}

+ {codeFrame ? : null} + {stack ?
{stack}
: null} +
+
+ ); +} + +function CodeFrame(props: { codeFrame: string }) { + const lines: ComponentChildren[] = []; + + colors.stripColor(props.codeFrame.trimEnd()).split("\n").forEach( + (line, i, arr) => { + const vnode = ( + ") ? " active-line" : "")} + > + {line} + + ); + + lines.push(vnode); + if (i < arr.length - 1) lines.push("\n"); + }, + ); + return ( +
+      {lines}
+    
+ ); +} diff --git a/tests/error_test.ts b/tests/error_test.ts index b6efc38a..a58ec770 100644 --- a/tests/error_test.ts +++ b/tests/error_test.ts @@ -2,7 +2,7 @@ import { ServerContext, Status } from "../server.ts"; import { assert, assertEquals, assertStringIncludes } from "./deps.ts"; import manifest from "./fixture_error/fresh.gen.ts"; -const ctx = await ServerContext.fromManifest(manifest, {}); +const ctx = await ServerContext.fromManifest(manifest, { dev: true }); const handler = ctx.handler(); const router = (req: Request) => { return handler(req, { @@ -20,10 +20,6 @@ Deno.test("error page rendered", async () => { assertEquals(resp.status, Status.InternalServerError); assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8"); const body = await resp.text(); - assertStringIncludes( - body, - `An error occurred during route handling or page rendering.`, - ); assertStringIncludes(body, `Error: boom!`); assertStringIncludes(body, `at render`); });