feat: improve default error visualization (#1780)
Adds code frame to errors if possible: <img width="1095" alt="Screenshot 2023-09-15 at 11 33 46" src="https://github.com/denoland/fresh/assets/1062408/7f4a5378-d00f-4550-b995-37a77f96ce0c"> Default error page in dev mode: <img width="937" alt="Screenshot 2023-09-15 at 11 30 59" src="https://github.com/denoland/fresh/assets/1062408/130172f4-beed-4d8c-b2b5-0e23be0b8f84"> Default error page in prod mode: <img width="939" alt="Screenshot 2023-09-15 at 11 31 23" src="https://github.com/denoland/fresh/assets/1062408/4ef58b83-b5f4-45cb-bc3f-1c8c4e5b6357">
This commit is contained in:
@@ -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
|
||||||
|
"
|
||||||
|
`;
|
||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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));
|
||||||
|
});
|
||||||
+16
-4
@@ -20,7 +20,7 @@ import {
|
|||||||
setDevMode,
|
setDevMode,
|
||||||
} from "./constants.ts";
|
} from "./constants.ts";
|
||||||
import { BUILD_ID, setBuildId } from "./build_id.ts";
|
import { BUILD_ID, setBuildId } from "./build_id.ts";
|
||||||
import DefaultErrorHandler from "./default_error_page.ts";
|
import DefaultErrorHandler from "./default_error_page.tsx";
|
||||||
import {
|
import {
|
||||||
AppModule,
|
AppModule,
|
||||||
BaseRoute,
|
BaseRoute,
|
||||||
@@ -63,6 +63,7 @@ import {
|
|||||||
} from "../build/mod.ts";
|
} from "../build/mod.ts";
|
||||||
import { InternalRoute } from "./router.ts";
|
import { InternalRoute } from "./router.ts";
|
||||||
import { setAllIslands } from "./rendering/preact_hooks.ts";
|
import { setAllIslands } from "./rendering/preact_hooks.ts";
|
||||||
|
import { getCodeFrame } from "./code_frame.ts";
|
||||||
|
|
||||||
const DEFAULT_CONN_INFO: ServeHandlerInfo = {
|
const DEFAULT_CONN_INFO: ServeHandlerInfo = {
|
||||||
localAddr: { transport: "tcp", hostname: "localhost", port: 8080 },
|
localAddr: { transport: "tcp", hostname: "localhost", port: 8080 },
|
||||||
@@ -798,7 +799,6 @@ export class ServerContext {
|
|||||||
if (route.component === undefined) {
|
if (route.component === undefined) {
|
||||||
throw new Error("This page does not have a component to render.");
|
throw new Error("This page does not have a component to render.");
|
||||||
}
|
}
|
||||||
|
|
||||||
const layouts = selectSharedRoutes(route.baseRoute, this.#layouts);
|
const layouts = selectSharedRoutes(route.baseRoute, this.#layouts);
|
||||||
|
|
||||||
const resp = await internalRender({
|
const resp = await internalRender({
|
||||||
@@ -898,7 +898,7 @@ export class ServerContext {
|
|||||||
this.#error,
|
this.#error,
|
||||||
Status.InternalServerError,
|
Status.InternalServerError,
|
||||||
);
|
);
|
||||||
const errorHandler: router.ErrorHandler<RouterState> = (
|
const errorHandler: router.ErrorHandler<RouterState> = async (
|
||||||
req,
|
req,
|
||||||
ctx,
|
ctx,
|
||||||
error,
|
error,
|
||||||
@@ -906,8 +906,20 @@ export class ServerContext {
|
|||||||
console.error(
|
console.error(
|
||||||
"%cAn error occurred during route handling or page rendering.",
|
"%cAn error occurred during route handling or page rendering.",
|
||||||
"color:red",
|
"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(
|
return this.#error.handler(
|
||||||
req,
|
req,
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -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),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -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 (
|
||||||
|
<div class="frsh-error-page">
|
||||||
|
<style id="fresh_error_styles">{errorCss}</style>
|
||||||
|
<div class="inner">
|
||||||
|
<h1 class="title">{title}</h1>
|
||||||
|
{codeFrame ? <CodeFrame codeFrame={codeFrame} /> : null}
|
||||||
|
{stack ? <pre class="stack">{stack}</pre> : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CodeFrame(props: { codeFrame: string }) {
|
||||||
|
const lines: ComponentChildren[] = [];
|
||||||
|
|
||||||
|
colors.stripColor(props.codeFrame.trimEnd()).split("\n").forEach(
|
||||||
|
(line, i, arr) => {
|
||||||
|
const vnode = (
|
||||||
|
<span
|
||||||
|
class={"line" + (line.startsWith(">") ? " active-line" : "")}
|
||||||
|
>
|
||||||
|
{line}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
|
||||||
|
lines.push(vnode);
|
||||||
|
if (i < arr.length - 1) lines.push("\n");
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<pre class="code-frame">
|
||||||
|
<code>{lines}</code>
|
||||||
|
</pre>
|
||||||
|
);
|
||||||
|
}
|
||||||
+1
-5
@@ -2,7 +2,7 @@ import { ServerContext, Status } from "../server.ts";
|
|||||||
import { assert, assertEquals, assertStringIncludes } from "./deps.ts";
|
import { assert, assertEquals, assertStringIncludes } from "./deps.ts";
|
||||||
import manifest from "./fixture_error/fresh.gen.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 handler = ctx.handler();
|
||||||
const router = (req: Request) => {
|
const router = (req: Request) => {
|
||||||
return handler(req, {
|
return handler(req, {
|
||||||
@@ -20,10 +20,6 @@ Deno.test("error page rendered", async () => {
|
|||||||
assertEquals(resp.status, Status.InternalServerError);
|
assertEquals(resp.status, Status.InternalServerError);
|
||||||
assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8");
|
assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8");
|
||||||
const body = await resp.text();
|
const body = await resp.text();
|
||||||
assertStringIncludes(
|
|
||||||
body,
|
|
||||||
`An error occurred during route handling or page rendering.`,
|
|
||||||
);
|
|
||||||
assertStringIncludes(body, `Error: boom!`);
|
assertStringIncludes(body, `Error: boom!`);
|
||||||
assertStringIncludes(body, `at render`);
|
assertStringIncludes(body, `at render`);
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user