Function: toHttpError()
toHttpError(
error):NormalizedHttpError|undefined
Defined in: httpError.ts:96
Normalizes an error thrown by a library middleware — authMiddleware,
createMcpRouter's auth, or any ctx.throw — into the status, message,
and headers a catch-all error middleware must preserve.
An app with its own error envelope typically recognizes only its own error
class and turns everything else into a 500. That swallows a deliberate
401 and its WWW-Authenticate header, which is the whole RFC 9728
discovery chain for MCP clients: the client gets an opaque server error where
it expected the pointer to the authorization server, so OAuth discovery never
starts. Run thrown values through this helper before falling back to 500.
Returns undefined for anything that is not a deliberate, exposable 4xx —
a genuine bug still becomes a 500 with nothing leaked. Only errors that opt
in via expose === true (which http-errors sets for 4xx) pass through.
Parameters
| Parameter | Type |
|---|---|
error | unknown |
Returns
NormalizedHttpError | undefined
Example
import { applyHttpErrorHeaders, toHttpError } from '@ttoss/http-server';
app.use(async (ctx, next) => {
try {
await next();
} catch (error) {
if (error instanceof ApiError) {
writeError(ctx, error);
return;
}
const httpError = toHttpError(error);
if (httpError) {
applyHttpErrorHeaders({ ctx, error });
writeError(ctx, new ApiError(httpError.status, httpError.message));
return;
}
console.error('Unhandled request error:', error);
writeError(ctx, new ApiError(500, 'internal_error'));
}
});