Add 403 + 500 error templates (todo §0); render 500 via app error handler
This commit is contained in:
24
src/app.ts
24
src/app.ts
@@ -1,4 +1,4 @@
|
||||
import { createServer, type Server } from "node:http";
|
||||
import { createServer, type Server, type ServerResponse } from "node:http";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import * as ejs from "ejs";
|
||||
@@ -18,6 +18,11 @@ export function createApp(options: AppOptions = {}): Server {
|
||||
const render = (view: string, data: Record<string, unknown>): Promise<string> =>
|
||||
ejs.renderFile(join(viewsDir, `${view}.ejs`), data);
|
||||
|
||||
const sendHtml = (res: ServerResponse, status: number, html: string): void => {
|
||||
res.writeHead(status, { "content-type": "text/html; charset=utf-8" });
|
||||
res.end(html);
|
||||
};
|
||||
|
||||
return createServer(async (req, res) => {
|
||||
try {
|
||||
if (req.method !== "GET" && req.method !== "HEAD") {
|
||||
@@ -33,17 +38,22 @@ export function createApp(options: AppOptions = {}): Server {
|
||||
}
|
||||
|
||||
if (pathname === "/") {
|
||||
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
||||
res.end(await render("index", { title: "Plainpages" }));
|
||||
sendHtml(res, 200, await render("index", { title: "Plainpages" }));
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(404, { "content-type": "text/html; charset=utf-8" });
|
||||
res.end(await render("404", { title: "Not found" }));
|
||||
sendHtml(res, 404, await render("404", { title: "Not found" }));
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
if (!res.headersSent) res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
|
||||
res.end("Internal Server Error");
|
||||
if (res.headersSent) return void res.end(); // a partial body is already on the wire
|
||||
try {
|
||||
// Render first: if the error page itself fails, headers stay unsent and we
|
||||
// fall back to plain text below rather than emit a half-written response.
|
||||
sendHtml(res, 500, await render("500", { title: "Server error" }));
|
||||
} catch (renderErr) {
|
||||
console.error(renderErr);
|
||||
res.writeHead(500, { "content-type": "text/plain; charset=utf-8" }).end("Internal Server Error");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user