53 lines
1.4 KiB
TypeScript
53 lines
1.4 KiB
TypeScript
import { type ProblemDetails, problem, problemTypes } from '@superlist/shared'
|
|
import type { Context } from 'hono'
|
|
import { HTTPException } from 'hono/http-exception'
|
|
|
|
import { logger } from '@/lib/logger'
|
|
|
|
/** Writes a RFC 9457 Problem Details response (`application/problem+json`). */
|
|
export function problemResponse(_c: Context, details: ProblemDetails) {
|
|
return new Response(JSON.stringify(details), {
|
|
status: details.status,
|
|
headers: { 'content-type': 'application/problem+json' },
|
|
})
|
|
}
|
|
|
|
/** Maps anything thrown inside a handler to a Problem Details response. */
|
|
export function errorHandler(error: Error, c: Context) {
|
|
if (error instanceof HTTPException) {
|
|
return problemResponse(
|
|
c,
|
|
problem({
|
|
title: error.message,
|
|
status: error.status,
|
|
detail: error.cause instanceof Error ? error.cause.message : undefined,
|
|
}),
|
|
)
|
|
}
|
|
|
|
logger.error({ err: error, path: c.req.path }, 'unhandled error')
|
|
|
|
return problemResponse(
|
|
c,
|
|
problem({
|
|
type: problemTypes.internal,
|
|
title: 'Internal Server Error',
|
|
status: 500,
|
|
detail: 'An unexpected error happened while processing the request.',
|
|
}),
|
|
)
|
|
}
|
|
|
|
/** Fallback for unmatched routes. */
|
|
export function notFoundHandler(c: Context) {
|
|
return problemResponse(
|
|
c,
|
|
problem({
|
|
type: problemTypes.notFound,
|
|
title: 'Not Found',
|
|
status: 404,
|
|
detail: `No route matches ${c.req.method} ${c.req.path}`,
|
|
}),
|
|
)
|
|
}
|