refactor: improve error handling with global router catchall

This commit is contained in:
Nicolas Meienberger
2025-09-24 17:44:41 +02:00
parent db88bb6de2
commit 677db2f90f
16 changed files with 321 additions and 361 deletions

View File

@@ -1,5 +1,4 @@
import { ConflictError, NotFoundError } from "http-errors-enhanced";
import { logger } from "./logger";
export const handleServiceError = (error: unknown) => {
if (error instanceof ConflictError) {
@@ -10,8 +9,7 @@ export const handleServiceError = (error: unknown) => {
return { message: error.message, status: 404 as const };
}
logger.error("Unhandled service error:", error);
return { message: "Internal Server Error", status: 500 as const };
return { message: toMessage(error), status: 500 as const };
};
export const toMessage = (err: unknown): string => {

View File

@@ -0,0 +1,53 @@
import path from "node:path";
import fs from "node:fs/promises";
type MountInfo = {
mountPoint: string;
fstype: string;
};
function isPathWithin(base: string, target: string): boolean {
const rel = path.posix.relative(base, target);
return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
}
function unescapeMount(s: string): string {
return s.replace(/\\([0-7]{3})/g, (_, oct) => String.fromCharCode(parseInt(oct, 8)));
}
async function readMountInfo(): Promise<MountInfo[]> {
const text = await fs.readFile("/proc/self/mountinfo", "utf-8");
const result: MountInfo[] = [];
for (const line of text.split("\n")) {
if (!line) continue;
const sep = line.indexOf(" - ");
if (sep === -1) continue;
const left = line.slice(0, sep).split(" ");
const right = line.slice(sep + 3).split(" ");
// [0]=mount ID, [1]=parent ID, [2]=major:minor, [3]=root, [4]=mount point, [5]=mount options, ...
const mpRaw = left[4];
const fstype = right[0];
if (!mpRaw || !fstype) continue;
result.push({ mountPoint: unescapeMount(mpRaw), fstype });
}
return result;
}
export async function getMountForPath(p: string): Promise<MountInfo | undefined> {
const mounts = await readMountInfo();
let best: MountInfo | undefined;
for (const m of mounts) {
if (!isPathWithin(m.mountPoint, p)) continue;
if (!best || m.mountPoint.length > best.mountPoint.length) {
best = m;
}
}
return best;
}