lukeed / polka

A micro web server so fast, it'll make you dance! :dancers:
MIT License
5.43k stars 174 forks source link

How can I handle global errors like express? #184

Closed TheVegeta closed 2 years ago

TheVegeta commented 2 years ago

I want to handle global errors like express, but I can not find any way to handle global errors in the current version of polka.

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

All I can find is this thread, but it is not supported in recent versions of polka since we can not create a custom server with http.

https://github.com/lukeed/polka/issues/12#issuecomment-359166629

Is it possible to handle global errors like express?

lukeed commented 2 years ago

options.onError

and you can still use custom server too, see options.server

TheVegeta commented 2 years ago

Hello, thanks for your reply.

The main issue here is that it is catching my errors but the server is crashing and I can not find any way to prevent server crashes.

I also attempted to run this code, but it still generates errors and crashes the server. https://github.com/lukeed/polka/issues/12#issuecomment-486089751

If you are wondering about my code, it is here but I can not hit the main route and it will always give me an error hanling route in response. https://github.com/TheVegeta/esbuild-polka-starter/blob/main/src/index.js

If I am doing something wrong, please correct me.

lukeed commented 2 years ago

1) use polka@next 2) youre doing app.handler = handleErr, which is NOT the same thing as the comment from #12 – because here is your handleErr code:

export const handleErr = (req, res, err) => {
  res.statusCode = 500;
  res.setHeader("content-type", "application/json").end(
    jsonStringify({
      success: false,
      msg: "something went wrong on server",
      data: {},
    })
  );
};

This means every route is going to reply with a 500 "something went wrong on server" response because your handleErr isn't wrapping original route handlers... it's replacing them with a forced 500 error.

TheVegeta commented 2 years ago

Unfortunately, I can not figure out how to implement this on my own, so it would be great if you could add an example of how to handle errors and send error responses with custom json.

If you could add an example, it would be much help.

lukeed commented 2 years ago

12 is an example. You copied it incorrectly

TheVegeta commented 2 years ago

Thank you for pointing it out. And for your reply, I figured it out and implemented it in the code.