unjs / h3

⚡️ Minimal H(TTP) framework built for high performance and portability

Home Page:https://h3.unjs.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Global hooks are not called when an error is thrown

antoinerey opened this issue · comments

Environment

h3: latest (1.11.1)
node: v18.18.0 (on Stackblitz), and v20.10.0 (on my machine)

Reproduction

The full reproduction is here https://stackblitz.com/edit/unjs-h3-bql2cu.

export const app = createApp({
  onRequest(event) {
    console.log('onRequest');
    console.log(event.path);
    console.log(getResponseStatus(event));
  },

  onError(error, event) {
    console.log('onError');
    console.log(event.path);
    console.log(getResponseStatus(event));
  },

  onBeforeResponse(event) {
    console.log('onBeforeResponse');
    console.log(event.path);
    console.log(getResponseStatus(event));
  },

  onAfterResponse(event) {
    console.log('onAfterResponse');
    console.log(event.path);
    console.log(getResponseStatus(event));
  },
});

app.use(
  '/',
  eventHandler((event) => {
    throw createError({
      message: 'Oops',
      statusCode: 500,
    });
  })
);

Describe the bug

With the above setup, loading / produces logs from the onRequest hook, but that's it. I would expect to have onError called (at least), and likely onBeforeResponse and onAfterResponse since a response is sent anyway.

Additional context

I'm not deeply familiar with h3, but I've been trying to dig deeper following another issue I've created on Nuxt side: nuxt/nuxt#26113.

So, I've set this reproduction up, and I'm now confused as no hook but onRequest is called. I might be missing something, but I've read the documentation and browsed issues, and could not find anything obvious.

Logs

No response

@antoinerey I think it's a listhen problem.

Because it works ↓

node app.mjs
// app.mjs
import { createServer } from "node:http";
import {
  createApp,
  createError,
  eventHandler,
  getResponseStatus,
  toNodeListener,
} from "h3";

export const app = createApp({
  onRequest(event) {
    console.log("onRequest");
    console.log(event.path);
    console.log(getResponseStatus(event));
  },

  onError(error, event) {
    console.log("onError");
    console.log(event.path);
    console.log(getResponseStatus(event));
  },

  onBeforeResponse(event) {
    console.log("onBeforeResponse");
    console.log(event.path);
    console.log(getResponseStatus(event));
  },

  onAfterResponse(event) {
    console.log("onAfterResponse");
    console.log(event.path);
    console.log(getResponseStatus(event));
  },
});

app.use(
  "/",
  eventHandler((event) => {
    throw createError({
      message: "Oops",
      statusCode: 500,
    });
  }),
);

createServer(toNodeListener(app)).listen(3000);

but not with listhen.

This should be fixed via #756