lau1944/bunrest

Catch 404 request.

LenoirRemi opened this issue · 5 comments

Hi Developers,

I would like to know if there is a way to catch bad requests?

Let's say I have this code:

import server from "bunrest";
const app = server();

app.get('/', (req, res) => {
    res.status(200).json({
        message: 'API Root'
    });
});

export default app;

Obviously calling localhost:3000/ gives me {"message":"API Root"}.

But if I try to reach a non-handled route (like localhost:3000/abcd), it gives me that:
Welcome to Bun! To get started, return a Response object.

Is there a way to catch bad requests as in express?

Like in this example: https://expressjs.com/en/starter/faq.html by adding a middleware function at the very bottom of the stack (below all other functions):

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

Best Regards

This in fact is a bug, I did not handle invalid path on my code. thank you for pointing that out!
I had fixed the code on newest version 1.1.4, any invalid path will throw an error.

If you want to catch an error globally, you can do it like this.

app.use((req, res, next, err) => {
    if (err) {
       res.status(500).send('Error happened');
   }
 });

Or it will simply throw an error
Cannot find path on /abdc

It works like a charm, Wonderful !
Many thanks

I'm on version 1.2.0 and I get "Welcome to Bun! To get started, return a Response object." on unhandled routes.

I'm on version 1.2.0 and I get "Welcome to Bun! To get started, return a Response object." on unhandled routes.

Aware of this issue, working on it...

Fixed in the latest version @YaredFall