fastify / fastify/fastify-websocket
Throwing an error in wsHandler causes the node process to exit
- Dominant language
- JavaScript
- Stars
- 468
- Forks
- 84
- PR merge metrics
- No merged PRs in 30d
Description
### Prerequisites
- [X] I have written a descriptive issue title
- [X] 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.
```ts
...(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");
}
},
}
: {}),
```
```ts
// 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
Contributor guide
Assessment
This issue has not been assessed yet.