Skip to content

Commit

Permalink
fix: Improve error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
TheCommieAxolotl committed Aug 16, 2023
1 parent 176b6e6 commit fdbb444
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 23 deletions.
4 changes: 2 additions & 2 deletions src/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import { App, AppDetails } from "../types";

import { Server } from "node:http";

import { ANSI, color } from "../util/logger";
import { Route } from "../router/route";
import { startServer } from "./server";
import { color } from "../util/logger";
import { use } from "./use";

/**
Expand All @@ -23,7 +23,7 @@ export const app = (options: number | Server, log = true): App => {
const attach = (route: Route): boolean => {
_routes.add(route);

if (log) console.log(` - ${color(route.path, "blue")}`);
if (log) console.log(` - ${color(route.path, ANSI.blue)}`);

return true;
};
Expand Down
10 changes: 5 additions & 5 deletions src/app/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { App } from "../types";

import https, { Server } from "node:http";

import { ANSI, log } from "../util/logger";
import { handleRequest } from "../router";
import { log } from "../util/logger";

export const startServer = (app: Partial<App>, doLog = true) => {
let server: Server;
Expand All @@ -23,18 +23,18 @@ export const startServer = (app: Partial<App>, doLog = true) => {
if (doLog) {
log(
`Listening${app.details["port"] ? ` on http://localhost:${app.details["port"]}/` : " to Server"}`,
"magenta"
ANSI.magenta
);
log(`Press Ctrl+C to exit process.`, "yellow");
log(`Press Ctrl+C to exit process.`, ANSI.yellow);
log("");
log("Page Routes", "bold");
log("Page Routes", ANSI.bold);
}

return () => {
return new Promise<boolean>((resolve) => {
if (server.listening) {
server.close(() => {
if (doLog) log("Server closed.", "red");
if (doLog) log("Server closed.", ANSI.red);

resolve(true);
});
Expand Down
43 changes: 37 additions & 6 deletions src/aura/common.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { log } from "../util/logger";

export type MIME =
| "text/html"
| "application/json"
Expand Down Expand Up @@ -27,11 +29,30 @@ export type ResponseData = {
headers?: Record<string, string>;
};

const make = (type: MIME, content: string | TemplateStringsArray): ResponseData => ({
type,
content: String(content),
status: 200,
});
const make = (type: MIME, content: string | TemplateStringsArray | []): ResponseData => {
if (Array.isArray(content))
return {
type: "text/plain",
content: "Uncaught server error",
status: 500,
};

try {
return {
type,
content: String(content),
status: 200,
};
} catch (e) {
log(e as Error);

return {
type: "text/plain",
content: "Uncaught server error",
status: 500,
};
}
};

export const error = (status: number, content: string | TemplateStringsArray) => ({
type: "text/plain",
Expand All @@ -52,7 +73,17 @@ export const html = (content: string | TemplateStringsArray) => make("text/html"
* Create a response object for JSON content.
*/
export const json = (content: object | string | TemplateStringsArray) =>
make("application/json", typeof content === "string" ? content : JSON.stringify(content));
make(
"application/json",
(() => {
try {
return typeof content === "string" ? content : JSON.stringify(content);
} catch (e) {
log(e as Error);
return [];
}
})()
);
/**
* Create a response object for plaintext content.
*/
Expand Down
22 changes: 13 additions & 9 deletions src/util/logger.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export enum ASCII {
export enum ANSI {
reset = "\x1b[0m",
bold = "\x1b[1m",
dim = "\x1b[2m",
Expand All @@ -24,34 +24,38 @@ export enum ASCII {
bg_white = "\x1b[47m",
}

export const log = (message: string, ...colors: (keyof typeof ASCII)[]): void => {
export const log = (message: string | Error, ...colors: ANSI[]): void => {
if (message instanceof Error) {
message = `\n${color(" ERROR ", ANSI.bg_red)} ${message.message}`;
}

console.log(
colors
.map((color) => {
if (color.toLowerCase() in ASCII) {
return ASCII[color.toLowerCase()];
if (color.toLowerCase() in ANSI) {
return ANSI[color.toLowerCase()];
} else {
return color;
}
})
.join("") +
message +
ASCII.reset
ANSI.reset
);
};

export const color = (message: string, ...colors: string[]): string => {
export const color = (message: string, ...colors: ANSI[]): string => {
return (
colors
.map((color) => {
if (color.toLowerCase() in ASCII) {
return ASCII[color.toLowerCase()];
if (color.toLowerCase() in ANSI) {
return ANSI[color.toLowerCase()];
} else {
return color;
}
})
.join("") +
message +
ASCII.reset
ANSI.reset
);
};
8 changes: 7 additions & 1 deletion test/standalone.run.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,13 @@ server.attach(route("/", () => html`<h1>Hello World</h1>`));
server.attach(route("/json", () => json({ hello: "world" })));

server.attach(
route("/[path]", () => {
route("/path/[e]", (e) => {
return json(e);
})
);

server.attach(
route("/[...404]", () => {
return status(404);
})
);

0 comments on commit fdbb444

Please sign in to comment.