fix: show original error page in dev (#2074)

This commit is contained in:
Marvin Hagemeister
2023-11-28 11:58:50 +01:00
committed by GitHub
parent a8dfdd0b91
commit 9ee6ab72e0
11 changed files with 352 additions and 196 deletions
+9
View File
@@ -92,3 +92,12 @@ function handleError(e: Event) {
setTimeout(connect, 1000);
}
}
addEventListener("message", (ev) => {
if (ev.origin !== location.origin) return;
if (typeof ev.data !== "string" || ev.data !== "close-error-overlay") {
return;
}
document.querySelector("#fresh-error-overlay")?.remove();
});
+1
View File
@@ -2,6 +2,7 @@ import { INTERNAL_PREFIX } from "../runtime/utils.ts";
import { BUILD_ID } from "./build_id.ts";
export const DEV_CLIENT_URL = `${INTERNAL_PREFIX}/fresh_dev_client.js`;
export const DEV_ERROR_OVERLAY_URL = `${INTERNAL_PREFIX}/error_overlay`;
export const ALIVE_URL = `${INTERNAL_PREFIX}/alive`;
export const JS_PREFIX = `/js`;
export const DEBUG = !Deno.env.get("DENO_DEPLOYMENT_ID");
+63 -2
View File
@@ -1,6 +1,6 @@
import { extname, Status, typeByExtension } from "./deps.ts";
import * as router from "./router.ts";
import { FreshConfig, Manifest } from "./mod.ts";
import { FreshConfig, Manifest, UnknownHandlerContext } from "./mod.ts";
import { ALIVE_URL, DEV_CLIENT_URL, JS_PREFIX } from "./constants.ts";
import { BUILD_ID } from "./build_id.ts";
@@ -37,6 +37,7 @@ import {
} from "./compose.ts";
import { extractRoutes, FsExtractResult } from "./fs_extract.ts";
import { loadAotSnapshot } from "../build/aot_snapshot.ts";
import { ErrorOverlay } from "./error_overlay.tsx";
const DEFAULT_CONN_INFO: ServeHandlerInfo = {
localAddr: { transport: "tcp", hostname: "localhost", port: 8080 },
@@ -476,6 +477,64 @@ export class ServerContext {
);
};
if (this.#dev) {
const baseRoute = toBaseRoute("/_frsh/error_overlay");
internalRoutes["/_frsh/error_overlay"] = {
baseRoute,
methods: {
default: async (req, ctx) => {
if (
req.headers.get("referrer")?.includes("/_frsh/error_overlay")
) {
throw new Error("fail");
}
const resp = await internalRender({
request: req,
context: ctx,
route: {
component: ErrorOverlay,
inheritLayouts: false,
appWrapper: false,
csp: false,
url: req.url,
name: "error overlay route",
handler: (_req: Request, ctx: UnknownHandlerContext) =>
ctx.render(),
baseRoute,
pattern: baseRoute,
},
plugins: this.#plugins,
app: this.#extractResult.app,
layouts: [],
imports: [],
dependenciesFn: () => [],
renderFn: this.#renderFn,
url: new URL(req.url),
params: {},
data: undefined,
state: {
...ctx?.state,
error: null,
},
error: null,
codeFrame: undefined,
});
if (resp instanceof Response) {
return resp;
}
return sendResponse(resp, {
status: 200,
isDev: this.#dev,
statusText: undefined,
headers: undefined,
});
},
},
};
}
return { internalRoutes, staticRoutes, routes, otherHandler, errorHandler };
}
@@ -531,7 +590,9 @@ export class ServerContext {
if (!contents) return new Response(null, { status: 404 });
const headers: Record<string, string> = {
"Cache-Control": "public, max-age=604800, immutable",
"Cache-Control": this.#dev
? "no-cache, no-store, max-age=0, must-revalidate"
: "public, max-age=604800, immutable",
};
const contentType = typeByExtension(extname(params.path));
+5 -128
View File
@@ -1,134 +1,11 @@
import { ComponentChildren, h } from "preact";
import { DEBUG } from "./constants.ts";
import type { ErrorPageProps, RouteConfig } from "./types.ts";
import { colors } from "./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;
margin-bottom: 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;
codeFrame = props.codeFrame;
stack = error.stack ?? "";
} else {
title = String(error);
}
}
export default function DefaultErrorPage() {
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 style="max-width: 48rem; padding: 2rem 1rem; margin: 0 auto; font-family: sans-serif">
<h1>
An error occurred during route handling or page rendering.
</h1>
</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>
);
}
+164
View File
@@ -0,0 +1,164 @@
import { ComponentChildren, h } from "preact";
import { render } from "./render.ts";
import { PageProps } from "../server/mod.ts";
// Just to get some syntax highlighting
const css = (arr: TemplateStringsArray, ...exts: never[]) => {
if (exts.length) throw new Error("Not allowed");
return arr[0];
};
export 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;
padding: 0;
margin: 0;
}
@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;
margin-bottom: 1rem;
}
.code-frame {
overflow: auto;
padding: 0.5rem;
margin-bottom: 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;
}
.close-btn {
position: absolute;
top: 1rem;
right: 1rem;
color: var(--title);
display: block;
width: 3rem;
height: 3rem;
background: none;
border: none;
transform: translate3d(0, 0, 0);
}
.close-btn:active {
transform: translate3d(0, 2px, 0);
}
.close-btn:hover {
cursor: pointer;
filter: drop-shadow(0 0 0.75rem crimson);
}
`;
function CodeFrame(props: { codeFrame: string }) {
const lines: ComponentChildren[] = [];
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>
);
}
export function ErrorOverlay(props: PageProps) {
const url = props.url;
const title = url.searchParams.get("message") || "Internal Server Error";
const stack = url.searchParams.get("stack");
const codeFrame = url.searchParams.get("code-frame");
return (
<>
<div class="frsh-error-page">
<style dangerouslySetInnerHTML={{ __html: errorCss }} />
<div class="inner">
<div class="header">
<button class="close-btn" aria-label="close" id="close-btn">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth={1.5}
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M9.75 9.75l4.5 4.5m0-4.5l-4.5 4.5M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
</button>
</div>
<div>
<h1 class="title">{title}</h1>
{codeFrame ? <CodeFrame codeFrame={codeFrame} /> : null}
{stack ? <pre class="stack">{stack}</pre> : null}
</div>
</div>
</div>
<script
dangerouslySetInnerHTML={{
__html:
`document.querySelector("#close-btn").addEventListener("click", () => parent.postMessage("close-error-overlay"));`,
}}
/>
</>
);
}
+26
View File
@@ -18,6 +18,8 @@ import { ContentSecurityPolicy } from "../runtime/csp.ts";
import { RenderState } from "./rendering/state.ts";
import { renderHtml, renderOuterDocument } from "./rendering/template.tsx";
import { renderFreshTags } from "./rendering/fresh_tags.tsx";
import { DEV_ERROR_OVERLAY_URL } from "./constants.ts";
import { colors } from "./deps.ts";
export const DEFAULT_RENDER_FN: RenderFunction = (_ctx, render) => {
render();
@@ -364,6 +366,30 @@ export async function render<Data>(
pluginRenderResults: renderResults,
});
// Append error overlay
if (opts.error !== undefined && opts.url.pathname !== DEV_ERROR_OVERLAY_URL) {
const url = new URL(DEV_ERROR_OVERLAY_URL, "https://localhost/");
if (opts.error instanceof Error) {
let message = opts.error.message;
const idx = message.indexOf("\n");
if (idx > -1) message = message.slice(0, idx);
url.searchParams.append("message", message);
if (opts.error.stack) {
const stack = colors.stripAnsiCode(opts.error.stack);
url.searchParams.append("stack", stack);
}
} else {
url.searchParams.append("message", String(opts.error));
}
if (opts.codeFrame) {
const codeFrame = colors.stripAnsiCode(opts.codeFrame);
url.searchParams.append("code-frame", codeFrame);
}
result.bodyHtml +=
`<iframe id="fresh-error-overlay" src="${url.pathname}?${url.searchParams.toString()}" style="unset: all; position: fixed; top: 0; left: 0; z-index: 99999; width: 100%; height: 100%; border: none;"></iframe>`;
}
// Render outer document up to `<body>`
const html = renderOuterDocument(renderState, {
bodyHtml: result.bodyHtml,
+20 -31
View File
@@ -6,6 +6,7 @@ import {
assertTextMany,
assertTextMatch,
fetchHtml,
getErrorOverlay,
waitForStyle,
withFakeServe,
withFresh,
@@ -25,18 +26,14 @@ Deno.test({
},
});
Deno.test({
name: "dev_command config: shows codeframe",
async fn() {
await withFakeServe(
"./tests/fixture_dev_config/dev.ts",
async (server) => {
const doc = await server.getHtml("/codeframe");
assertSelector(doc, ".frsh-error-page");
assertSelector(doc, ".code-frame");
},
);
},
Deno.test("dev_command config: shows codeframe", async () => {
await withFakeServe(
"./tests/fixture_dev_config/dev.ts",
async (server) => {
const { codeFrame } = await getErrorOverlay(server, "/codeframe");
assert(codeFrame);
},
);
});
Deno.test({
@@ -52,18 +49,14 @@ Deno.test({
},
});
Deno.test({
name: "dev_command legacy: shows codeframe",
async fn() {
await withFakeServe(
"./tests/fixture_dev_legacy/dev.ts",
async (server) => {
const doc = await server.getHtml("/codeframe");
assertSelector(doc, ".frsh-error-page");
assertSelector(doc, ".code-frame");
},
);
},
Deno.test("dev_command legacy: shows codeframe", async () => {
await withFakeServe(
"./tests/fixture_dev_legacy/dev.ts",
async (server) => {
const { codeFrame } = await getErrorOverlay(server, "/codeframe");
assert(codeFrame);
},
);
});
Deno.test("preact/debug is active in dev mode", async () => {
@@ -72,15 +65,11 @@ Deno.test("preact/debug is active in dev mode", async () => {
async (server) => {
// SSR error is shown
const resp = await server.get("/");
const text = await resp.text();
await resp.text(); // Consume
assertEquals(resp.status, Status.InternalServerError);
assertStringIncludes(text, "Objects are not valid as a child");
const html = await server.getHtml("/");
// Error page is shown with error message
const text2 = html.querySelector(".frsh-error-page")!.textContent!;
assertStringIncludes(text2, "Objects are not valid as a child");
const { title } = await getErrorOverlay(server, "/");
assertStringIncludes(title, "Objects are not valid as a child");
},
);
});
+13 -22
View File
@@ -1,25 +1,16 @@
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, { dev: true });
const handler = ctx.handler();
const router = (req: Request) => {
return handler(req, {
remoteAddr: {
transport: "tcp",
hostname: "127.0.0.1",
port: 80,
},
});
};
import { Status } from "../server.ts";
import { assertEquals, assertStringIncludes } from "./deps.ts";
import { getErrorOverlay, withFakeServe } from "./test_utils.ts";
Deno.test("error page rendered", async () => {
const resp = await router(new Request("https://fresh.deno.dev/"));
assert(resp);
assertEquals(resp.status, Status.InternalServerError);
assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8");
const body = await resp.text();
assertStringIncludes(body, `Error: boom!`);
assertStringIncludes(body, `at render`);
await withFakeServe("./tests/fixture_error/dev.ts", async (server) => {
const resp = await server.get("/");
assertEquals(resp.status, Status.InternalServerError);
assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8");
await resp.text(); // Consume
const { title, stack } = await getErrorOverlay(server, "/");
assertStringIncludes(title, `boom!`);
assertStringIncludes(stack, `at render`);
});
});
+18 -11
View File
@@ -2,9 +2,8 @@ import { assert, assertEquals, assertStringIncludes, Page } from "./deps.ts";
import {
assertNoPageComments,
assertNotSelector,
assertSelector,
assertTextMatch,
clickWhenListenerReady,
getErrorOverlay,
parseHtml,
waitForText,
withFakeServe,
@@ -417,20 +416,28 @@ Deno.test("throws when passing non-jsx children to an island", async (t) => {
await withFakeServe(
"./tests/fixture_island_nesting/dev.ts",
async (server) => {
const doc = await server.getHtml(`/island_invalid_children`);
const overlay1 = await getErrorOverlay(
server,
"/island_invalid_children",
);
assertStringIncludes(
overlay1.title,
"Invalid JSX child passed to island",
);
assertSelector(doc, ".frsh-error-page");
assertTextMatch(doc, "pre", /Invalid JSX child passed to island/);
const doc2 = await server.getHtml(`/island_invalid_children_fn`);
assertSelector(doc2, ".frsh-error-page");
assertTextMatch(doc2, "pre", /Invalid JSX child passed to island/);
const overlay2 = await getErrorOverlay(
server,
"/island_invalid_children_fn",
);
assertStringIncludes(
overlay2.title,
"Invalid JSX child passed to island",
);
await t.step("should not throw on valid children", async () => {
const doc2 = await server.getHtml(`/island_valid_children`);
assertNotSelector(doc2, ".frsh-error-page");
assertNotSelector(doc2, "#fresh-error-overlay");
});
},
);
+15 -2
View File
@@ -6,6 +6,7 @@ import {
assertNotSelector,
assertSelector,
assertTextMany,
getErrorOverlay,
parseHtml,
waitFor,
waitForText,
@@ -41,9 +42,21 @@ Deno.test(
await withFakeServe(
"./tests/fixture_partials/main.ts",
async (server) => {
const html = await server.getHtml("/partial_slot_inside_island");
const res = await server.get("/partial_slot_inside_island");
assertEquals(res.status, 500);
await res.text(); // Consume
},
);
await withFakeServe(
"./tests/fixture_partials/dev.ts",
async (server) => {
const { title } = await getErrorOverlay(
server,
"/partial_slot_inside_island",
);
assertMatch(
html.querySelector("h1")!.textContent!,
title,
/<Partial> components cannot be used inside islands/,
);
},
+18
View File
@@ -166,6 +166,24 @@ function _printDomNode(
return out;
}
export async function getErrorOverlay(
server: FakeServer,
url: string,
): Promise<{ title: string; codeFrame: boolean; stack: string }> {
const doc = await server.getHtml(url);
const iframe = doc.querySelector(
"#fresh-error-overlay",
) as HTMLIFrameElement;
const doc2 = await server.getHtml(iframe.src);
return {
title: doc2.querySelector(".title")!.textContent!,
codeFrame: doc2.querySelector(".code-frame") !== null,
stack: doc2.querySelector(".stack")!.textContent!,
};
}
export async function withFresh(
name: string | { name: string; options: Omit<Deno.CommandOptions, "args"> },
fn: (address: string) => Promise<void>,