unjs / nitro

Next Generation Server Toolkit. Create web servers with everything you need and deploy them wherever you prefer.
https://nitro.unjs.io
MIT License
5.83k stars 492 forks source link

Log route for exceptions #1736

Open septatrix opened 12 months ago

septatrix commented 12 months ago

Describe the feature

I am currently using Nuxt to write an application. As it is almost impossible to check for every eventuality during development there are sometimes exception logged on production. However, as everything is bundled, the stack traces are not really useful and do not give any hint as to which route was causing the problem.

In those cases it would greatly simplify troubleshooting if some information about the request is also logged for exceptions.

In some cases it is possible to find the handler file (./.output/server/chunks/foobar.get.mjs) listed as part of the stack trace though that is not always the case. For example I have to error messages [nuxt] [request error] [unhandled] [500] The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received an instance of URLSearchParams and [nuxt] [request error] [unhandled] [500] Cannot set headers after they are sent to the client where I do not know from which handler they originate. Therefore I am also not sure if this might be my fault or something within Nuxt which is failing - and I have no good way to create a reproducible example to figure that out and maybe raise a proper issue here.

Additional information

pi0 commented 12 months ago

Nice idea! We can achieve this using new Native Async Context and Error Capturing Hooks.

septatrix commented 12 months ago

Looking at the linked error hook announcement it seems like async context might not even be required. I will try to get it running with defineNitroPlugin() in Nuxt once I have a bit of time to play around the coming days

pi0 commented 12 months ago

Thanks but we definitely need ALS to track requests. Nitro plugins, unlike nuxt do not preserve context during per-request call (but run once during startup).

You might try something with error hook btw and log it in a nitro plugin with more error context, that's possible.

septatrix commented 12 months ago

Yeah I was referring to the latter. Basically what's already written in the error hook code snippet from the release announcement (except replacing hookOnce with hook):

export default defineNitroPlugin((nitro) => {
  nitro.hooks.hook('error', async (error, { event }) => {
    console.error(`${event.path} Application error:`, error)
  })
})
pi0 commented 12 months ago

Feel free to open a PR to unjs/website it must have been a typo with hookOnce!