Ka-Note/ka-note/server/src/lib/route-utils.ts

22 lines
779 B
TypeScript

import type { Context } from 'hono';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type AnyHandler = (c: Context<any>) => Promise<any>;
/**
* Wraps a route handler with structured error logging.
* Preserves the handler's generic type so Hono can infer env/input/output types correctly.
*/
export function handle<F extends AnyHandler>(label: string, fn: F): F {
return (async (c: Context<any>) => {
try {
return await fn(c);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
const stack = err instanceof Error ? err.stack : undefined;
console.error(`[${label}]`, c.req.method, c.req.path, msg, stack);
return c.json({ error: 'internal server error', detail: msg }, 500);
}
}) as F;
}