Skip to content

Throwing an error in wsHandler causes the node process to exit #308

Open
@AnzeKop

Description

@AnzeKop

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

5.1.0

Plugin version

11.0.01

Node.js version

20

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

Ubuntu 20

Description

When throwing an error in the websocket route (in our case this is when an unexpected close happens from the user) the node process seems to exit with status code 1 instead of just abandoning the connection causing the entire app to stop and then leads to unstable restarts when in our case Heroku tries to restart the app.

Example is this.

  ...(apiJob.server?.websocket === true
        ? {
            wsHandler: async (socket, request) => {
              try {
                const wsManager = new WebSocketServerManager(socket);

                const parseResult = apiJob.schema.safeParse(
                  unflattenParams(new URLSearchParams(request.query as any))
                );

                if (!parseResult.success) {
                  socket.close(4422, "Invalid payload structure.");
                  console.error(
                    `Invalid payload structure: ${JSON.stringify(
                      parseResult.error.errors,
                      null,
                      2
                    )}`
                  );
                  return;
                }

                await apiJob.server!.handler(parseResult.data as any, {
                  run: new Run({
                    cache: new KnexCache(),
                  }),
                  hubspotApi: await createClientWithAccessToken(),
                  jobId: request.id,
                  socket: wsManager,
                });
              } catch (error) {
                console.error(`Failed to process request:`, error);
                socket.close(4500, "An unknown error occurred");
              }
            },
          }
        : {}),
// inside the websocket server manager class

    this.socket.on("close", () => {
      this.cleanup();
      if (!this.expectedClose) {
        console.warn("WebSocket connection closed unexpectedly");
        throw new Error("WebSocket connection closed unexpectedly");
      }
    });

Link to code that reproduces the bug

No response

Expected Behavior

Throwing an error inside a socket handler stops any ongoing processes/function executions and just closes the connection.

If there is any better way to stop any ongoing execution I'm happy to hear suggestions

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions