(
err: Error,
c: Context<TEnv>,
)
| 189 | const MAX_UPSTREAM_BODY_LENGTH = 16000; |
| 190 | |
| 191 | export async function handleError<TEnv extends ErrorHandlerEnv>( |
| 192 | err: Error, |
| 193 | c: Context<TEnv>, |
| 194 | ) { |
| 195 | // Use getLogger directly instead of c.get("log"). The error handler must |
| 196 | // never depend on logger middleware having run successfully — getLogger is |
| 197 | // idempotent (returns the same singleton for the same category). |
| 198 | const log = getLogger(["hono"]); |
| 199 | const timestamp = new Date().toISOString(); |
| 200 | |
| 201 | // Set the error on the context for it to be tracked |
| 202 | c.set("error", err); |
| 203 | |
| 204 | if (err instanceof UpstreamError) { |
| 205 | const status = err.status; |
| 206 | if (status >= 500) |
| 207 | await emitServerError(c, err, status, timestamp, log); |
| 208 | else { |
| 209 | log.trace("UpstreamError: {message}", { |
| 210 | message: err.message || getDefaultErrorMessage(err.status), |
| 211 | }); |
| 212 | } |
| 213 | return c.json( |
| 214 | createUpstreamErrorResponse(err, status, timestamp), |
| 215 | status, |
| 216 | ); |
| 217 | } |
| 218 | |
| 219 | if (err instanceof HTTPException) { |
| 220 | const status = err.status; |
| 221 | if (status >= 500) |
| 222 | await emitServerError(c, err, status, timestamp, log); |
| 223 | else { |
| 224 | log.trace("HttpException: {message}", { |
| 225 | message: err.message || getDefaultErrorMessage(err.status), |
| 226 | }); |
| 227 | } |
| 228 | return c.json(createErrorResponse(err, status, timestamp), status); |
| 229 | } |
| 230 | |
| 231 | if (err instanceof APIError) { |
| 232 | const status = err.statusCode as ContentfulStatusCode; |
| 233 | if (status >= 500) |
| 234 | await emitServerError(c, err, status, timestamp, log); |
| 235 | else log.trace("APIError: {error}", { error: err }); |
| 236 | return c.json(createErrorResponse(err, status, timestamp), status); |
| 237 | } |
| 238 | |
| 239 | if (err instanceof ValidationError) { |
| 240 | const status = 400; |
| 241 | const response = createValidationErrorResponse(err, status, timestamp); |
| 242 | log.trace("ValidationError: {error}", { error: err }); |
| 243 | return c.json(response, status); |
| 244 | } |
| 245 | |
| 246 | const status = 500; |
| 247 | await emitServerError(c, err, status, timestamp, log); |
| 248 | const response = createInternalErrorResponse(err, status, timestamp); |
no test coverage detected