lukeed/polka

How can I handle global errors like express?

Closed this issue · 6 comments

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.

#12 (comment)

Is it possible to handle global errors like express?

options.onError

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

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.
#12 (comment)

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.

  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.

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.

12 is an example. You copied it incorrectly

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