Kind: Class
Source: src/http-exception.ts
HTTPException must be used when a fatal error such as authentication failure occurs.
HTTPException represents a fatal HTTP failure, such as an authentication error. Throw it when request handling must stop and an existing Response should be returned to the caller.
Extends: Error
Methods
| Method | Signature | Returns |
|---|---|---|
getResponse | getResponse() | Response |
Properties
| Property | Type |
|---|---|
res | Response |
status | ContentfulStatusCode |
Diagram
mermaidgraph LR A[Request handler] --> B{Fatal HTTP error?} B -- Yes --> C[Create Response] C --> D[Throw HTTPException] D --> E[getResponse] E --> F[Return Response] B -- No --> G[Continue handling]
Usage
tsimport { HTTPException } from './http-exception'
function requireAuthentication(token?: string): void {
if (!token) {
const response = new Response('Unauthorized', {
status: 401,
headers: {
'content-type': 'text/plain',
},
})
throw new HTTPException(response)
}
}
async function handleRequest(request: Request): Promise<Response> {
try {
requireAuthentication(request.headers.get('authorization') ?? undefined)
return new Response('OK')
} catch (error) {
if (error instanceof HTTPException) {
return error.getResponse()
}
throw error
}
}
AI Coding Instructions
- Throw
HTTPExceptiononly for fatal request failures that already have aResponseto return. - Build the response status, headers, and body before creating the exception.
- Catch
HTTPExceptionat the request-handling boundary and returngetResponse(). - Do not replace unrelated runtime errors with
HTTPException; allow unexpected errors to follow normal error handling.
Used by
12 references from 12 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example.
Imported by (12)
handler—src/middleware/basic-auth/index.ts:118bearerAuth—src/middleware/bearer-auth/index.ts:104handler—src/middleware/body-limit/index.ts:72csrf—src/middleware/csrf/index.ts:94IPRestrictionRule—src/middleware/ip-restriction/index.ts:38headerName—src/middleware/jwk/jwk.ts:81headerName—src/middleware/jwt/jwt.ts:81HTTPExceptionFunction—src/middleware/timeout/index.ts:10
…and 4 more.
Was this page helpful?