Hey guys, I implemented a global filter for websocket exceptions and it seems like the filter does kind of work as the errors are caught and don't break my backend anymore.
This is my filter and how I apply it:
@Catch(WsException)
export class GlobalWsExceptionFilter extends BaseWsExceptionFilter {
constructor() {
super();
}
catch(exception: WsException, host: any) {
const client = host.switchToWs().getClient();
// Handle the WsException and send an error message to the client
client.emit('error', exception.getError());
// Optionally, you can log the error or perform additional actions
console.log("Calling Exception Filter")
console.log(exception.message)
// Call the super method to finalize the exception handling
super.catch(exception, host);
}
}```
main.ts:
```async function bootstrap() {
const app = await NestFactory.create(AppModule)
app.enableCors({ origin: "http://localhost:3000", credentials: true })
app.use(cookieParser())
// app.useGlobalPipes(new CustomValidationPipe())
// app.useGlobalFilters(new CustomExceptionFilter())
app.useGlobalFilters(new HttpExceptionFilter(), new GlobalWsExceptionFilter())
await app.listen(8080)
}
bootstrap()```
I then on purpose throw the WsException in this handler:
@SubscribeMessage("startGame")
async handleStartGame(@ConnectedSocket() client: Socket, @MessageBody(new ValidationPipe()) startGameDto: StartGameDto) {
const lobby: PopulatedLobbyDocument = await this.lobbyService.findById(startGameDto.lobbyId)
if (!lobby) {
console.log("Throwing not found exception")
throw new WsException(errorMessagesInternationalized.lobbyNotFound)
}
return this.gameService.createGame(lobby)
}```
The exception seems to be thrown, as the print-command in the if-clause is executed but caught as it doesn't break my backend. It is confusing though as the print-commands in the filter aren't executed.