Middleware@rhythmjs/middleware
Filter exceptions
Wrap the chain in a try/catch: thrown HttpErrors become their status, everything else becomes a safe 500.
On this page
Catch everything downstream#
filter(onError?) wraps the rest of the chain in a try/catch and turns anything thrown downstream into an HTTP response. Register it first on the router, before any routes, so it forms the outermost onion layer of that router and sees every error, including ones thrown by other middleware.
import { RhythmRouter } from "@rhythmjs/router";
import { filter, HttpError } from "@rhythmjs/middleware/filter";
const router = new RhythmRouter().use(filter()).get("/users/:id", (ctx) => {
throw new HttpError(404, "user not found");
});
// GET /users/1 => 404 {"success":false,"status":404,"message":"user not found"}Put filter on the router, not on the app. mount(router) wraps anything thrown inside a mounted router in a new error (mounted router "name" failed) with the original as its cause, so an app-level filter() never sees your HttpError and answers a generic 500. The middleware is also typed for the HTTP context, which a plain new Rhythm() does not declare.
HttpError and the default mapping#
A thrown HttpError(status, message, details?) maps to its status with a JSON FilterFailure body; details is included only when defined, so simple errors stay small. Anything else thrown (a plain Error, a string, a rejected promise) maps to a generic 500 with the message "Internal Server Error": the original message is never leaked to the client, and the default mapping does not log it either; pass onError (below) to log.
throw new HttpError(422, "cannot ship yet", { missing: ["address"] });
// => 422 {"success":false,"status":422,"message":"cannot ship yet","details":{"missing":["address"]}}Custom error mapping#
Passing an onError(error, ctx) hook replaces the default mapping entirely: the hook is responsible for writing the response (or rethrowing). If it neither responds nor rethrows, nothing has been written and toFetchHandler answers 404. Use it to log, translate domain errors into statuses, or forward to an error tracker:
router.use(
filter(async (error, ctx) => {
log.error(error);
if (error instanceof NotFoundInDb) {
json(ctx, { success: false, status: 404, message: "not found" }, 404);
return;
}
throw error; // rethrow: mount wraps it, toFetchHandler rejects, errorToResponse maps it
}),
);Composing the three modules#
The modules compose freely on one router. filter goes first so it wraps everything; error responses are non-2xx, so intercept skips them; and validate runs per route ahead of the handler:
const router = new RhythmRouter()
.use(filter())
.use(intercept(PublicUser))
.post("/users", validate("body", createUser), async (ctx) => {
const user = await users.create(ctx.valid.body);
if (!user) throw new HttpError(409, "user already exists");
json(ctx, user);
});See the API reference for every export on the three subpaths.