Skip to content

HTTPException ​

When a fatal error occurs, Hono (and many ecosystem middleware) may throw an HTTPException. This is a custom Hono Error that simplifies returning error responses.

Throwing HTTPExceptions ​

You can throw your own HTTPExceptions by specifying a status code, and either a message or a custom response.

Custom Message ​

For basic text responses, just set the error message.

ts
import { 
HTTPException
} from 'hono/http-exception'
throw new
HTTPException
(401, {
message
: 'Unauthorized' })

Custom Response ​

For other response types, or to set response headers, use the res option. Note that the status passed to the constructor is the one used to create responses.

ts
import { 
HTTPException
} from 'hono/http-exception'
const
errorResponse
= new
Response
('Unauthorized', {
status
: 401, // this gets ignored
headers
: {
Authenticate
: 'error="invalid_token"',
}, }) throw new
HTTPException
(401, {
res
:
errorResponse
})

Cause ​

In either case, you can use the cause option to add arbitrary data to the HTTPException.

ts
app
.
post
('/login', async (
c
) => {
try { await
authorize
(
c
)
} catch (
cause
) {
throw new
HTTPException
(401, {
message
,
cause
})
} return
c
.
redirect
('/')
})

Handling HTTPExceptions ​

You can handle uncaught HTTPExceptions with app.onError. They include a getResponse method that returns a new Response created from the error status, and either the error message, or the custom response set when the error was thrown.

ts
import { 
HTTPException
} from 'hono/http-exception'
// ...
app
.
onError
((
err
,
c
) => {
if (
err
instanceof
HTTPException
) {
// Return the error response generated by HTTPException return
err
.
getResponse
()
} // For any other unexpected errors, log and return a generic 500 response
console
.
error
(
err
)
return
c
.
text
('Internal Server Error', 500)
})

WARNING

HTTPException.getResponse is not aware of Context. To include headers already set in Context, you must apply them to a new Response.

Released under the MIT License.