Effect CommunityEC
Effect Community3y ago
6 replies
attila

Handling RouteNotFound Error in Simple Router

I have the following server with a very simple router. If I hit a non-existent route, I get a 500 internal server error instead of the expected 404. Do I, as a user, have to handle the RouteNotFound error? If so, how?

My intuition says to add Http.router.catchTag("RouteNotFound", () => Http.response.empty({ status: 404 })) in the router pipe. But that does not typecheck becaue the Router at that point is a Router<never, never>. Any tips?

import * as Http from "@effect/platform-node/HttpServer";
import * as NodeContext from "@effect/platform-node/NodeContext";
import { runMain } from "@effect/platform-node/Runtime";
import { Effect, Layer, pipe } from "effect";
import { createServer } from "node:http";

const ServerLive = Http.server.layer(() => createServer(), { port: 3000 });

const router = pipe(
  Http.router.empty,
  Http.router.get("/", Http.response.text("Hello World"))
);

const HttpLive = pipe(
  router,
  Http.server.serve(Http.middleware.logger),
  Layer.scopedDiscard,
  Layer.use(ServerLive),
  Layer.use(NodeContext.layer)
);

pipe(
  Layer.launch(HttpLive),
  Effect.tapErrorCause(Effect.logError),
  runMain
);
Was this page helpful?