h3 icon indicating copy to clipboard operation
h3 copied to clipboard

Cannot track status codes

Open imslepov opened this issue 9 months ago • 0 comments

Environment

  • Node Version: v20.12.2
  • H3 Version: 1.11.1

Reproduction

See https://stackblitz.com/edit/github-d9z5tl?file=app.ts

Describe the bug

Forwarded from https://github.com/nuxt/nuxt/issues/27248

When I return an error in eventHandler's using createError, global hooks onBeforeResponse and onAfterResponse behave unexpectedly:

  • onBeforeResponse always returns res.statusCode equal to 200
  • onAfterResponse does not work in case of an error in the handler

This does not track the actual status codes that users may encounter. For example, in my app I cannot collect statistics in Prometheus metrics.

export const app = createApp({
  onBeforeResponse: (event) => {
    // will always be 200
    console.log('[beforeResponse]', event.node.res.statusCode);
  },
  onAfterResponse: (event) => {
    // not called
    console.log('[afterResponse]', event.node.res.statusCode);
  },
});

const router = createRouter();
app.use(router);

router.get(
  '/',
  eventHandler((event) => {
    return createError({ statusCode: 404 });
  })
);

Additional context

No response

Logs

No response

imslepov avatar May 17 '24 10:05 imslepov