Chapter 10
Error Handling
Handle missing routes and unexpected failures.
Error Handling
Not every request can succeed. Hono gives you places to handle expected missing pages and unexpected application errors.
Not found responses
Use c.notFound() when a matched route cannot find the requested resource.
app.get('/chapters/:slug', (c) => {
const chapter = getChapter(c.req.param('slug'))
if (!chapter) {
return c.notFound()
}
return c.json(chapter)
})
This book does that for missing chapter slugs, then uses app.notFound() to render the shared 404 page.
app.notFound((c) => {
c.status(404)
return c.render(<NotFoundPage />)
})
Application errors
Use app.onError() for errors that were thrown and not handled inside a route.
app.onError((err, c) => {
console.error(err)
return c.json({ error: 'Something went wrong' }, 500)
})
Keep production error responses brief. Log the detailed error on the server, but avoid sending stack traces or secrets to the browser.
Useful error shapes
APIs are easier to consume when errors have a consistent shape.
return c.json(
{
error: {
code: 'chapter_not_found',
message: 'That chapter does not exist.',
},
},
404
)
HTML routes can render friendly pages. JSON routes should return structured data that clients can handle.