sstur / nbit

A zero-dependency, strongly-typed web framework for Bun, Node and Cloudflare workers
66 stars 4 forks source link

How to add a 404 and error handler? #6

Closed ImLunaHey closed 1 year ago

ImLunaHey commented 1 year ago

What's the recommended way of adding a 404 and global error handler?

I'm trying to emulate this from express.

How do I handle 404 responses?

In Express, 404 responses are not the result of an error, so the error-handler middleware will not capture them. This behavior is because a 404 response simply indicates the absence of additional work to do; in other words, Express has executed all middleware functions and routes, and found that none of them responded. All you need to do is add a middleware function at the very bottom of the stack (below all other functions) to handle a 404 response:

app.use((req, res, next) => {
  res.status(404).send("Sorry can't find that!")
})

Add routes dynamically at runtime on an instance of express.Router() so the routes are not superseded by a middleware function.

How do I setup an error handler?

You define error-handling middleware in the same way as other middleware, except with four arguments instead of three; specifically with the signature (err, req, res, next):

app.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

~Related: https://github.com/sstur/nbit/issues/5~ Related: https://github.com/sstur/nbit/issues/4

sstur commented 1 year ago

What's the recommended way of adding a 404 and global error handler?

This is now supported in v0.9. You can add a custom 404 handler as follows:

import { attachRoutes, defineRoutes } from './application';
import * as handlers from './handlers';

const port = 3000;

const fallback = defineRoutes((app) => [
  app.route('*', '/*', (request) => {
    return new Response('Oops, not found!', { status: 404 });
  }),
]);

Bun.serve({
  port,
  fetch: attachRoutes(...Object.values(handlers), fallback),
});
sstur commented 1 year ago

Note: the other question from the Express docs you quoted, "How do I setup an error handler?" is not yet possible in this framework. Feel free to open a separate issue to track that if you need this functionality. I'll see about adding it.