exception handler

This commit is contained in:
Chris Wanstrath 2025-11-30 10:24:13 -08:00
parent 7c8d555483
commit 30c1f4b894

View File

@ -1,6 +1,6 @@
import { join } from 'path' import { join } from 'path'
import prettier from 'prettier' import prettier from 'prettier'
import { type Context, Hono } from 'hono' import { type Context, Hono, type Schema, type Env } from 'hono'
import { serveStatic } from 'hono/bun' import { serveStatic } from 'hono/bun'
import color from 'kleur' import color from 'kleur'
@ -18,14 +18,21 @@ export type HypeProps = {
reset?: boolean reset?: boolean
} }
export class Hype extends Hono { export class Hype<
E extends Env = Env,
S extends Schema = {},
BasePath extends string = '/'
> extends Hono<E, S, BasePath> {
props?: HypeProps
routesRegistered = false routesRegistered = false
props: HypeProps = {}
constructor(props?: HypeProps) { constructor(props?: HypeProps & ConstructorParameters<typeof Hono<E, S, BasePath>>[0]) {
super() super(props)
if (props) this.props = props if (props) {
const { pico, reset } = props
this.props = { pico, reset }
}
} }
registerRoutes() { registerRoutes() {
@ -50,6 +57,22 @@ export class Hype extends Hono {
console.log(fn(`${c.res.status}`), `${color.bold(method)} ${c.req.url} (${end - start}ms)`) console.log(fn(`${c.res.status}`), `${color.bold(method)} ${c.req.url} (${end - start}ms)`)
}) })
// exception handler
this.onError((err, c) => {
const isDev = process.env.NODE_ENV !== 'production'
return c.html(
`<!DOCTYPE html>
<html>
<body>
<h1>Error: ${err.message}</h1>
${isDev ? `<pre>${err.stack}</pre>` : '<p>An error occurred</p>'}
</body>
</html>`,
500
)
})
// prettify HTML output // prettify HTML output
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
this.use('*', async (c, next) => { this.use('*', async (c, next) => {
@ -102,7 +125,7 @@ export class Hype extends Hono {
Layout = (await import(layoutPath + `?t=${Date.now()}`)).default Layout = (await import(layoutPath + `?t=${Date.now()}`)).default
const page = await import(path + `?t=${Date.now()}`) const page = await import(path + `?t=${Date.now()}`)
const innerHTML = typeof page.default === 'function' ? <page.default req={c.req} /> : page.default const innerHTML = typeof page.default === 'function' ? <page.default c={c} req={c.req} /> : page.default
const withLayout = Layout ? <Layout props={this.props}>{innerHTML}</Layout> : innerHTML const withLayout = Layout ? <Layout props={this.props}>{innerHTML}</Layout> : innerHTML
return c.html(withLayout) return c.html(withLayout)
}) })