Home > Net >  Exception filter NestJS does not work when delegating
Exception filter NestJS does not work when delegating

Time:07-27

I am using a gateway to emit events.

For clarity reasons, I created files that make the link between services and this gateway.

For example, in gateway :

    @SubscribeMessage('createRoom')
    async createRoom(client: Socket, channel: newChannelDto) {
        this.chatService.createRoom(client, channel)
    }

In Chat service :

    async createRoom(client: Socket, channel: newChannelDto)
    {
        await this.channelService.createChannel(channel.chanName, client.data.user, channel.password, channel.private)
        client.join(channel.chanName)
        for (let [allUsers, socket] of this.gateway.activeUsers.entries())
            this.gateway._server.to(socket.id).emit('rooms', " get rooms ", await this.channelService.getChannelsForUser(allUsers));
    }

where :

  • gateway is the injected gateway, and _server, declared as
@WebSocketServer()
    public _server : Server

the server contained in Gateway.

I made a WS/HTTP/Query failed exception filter, included on top of my Gateway via @UseFilters(new MyCustomExceptionsFilter()).

Before I move functions to the "children" files, my filter was able to catch everything, but since I moved them away from gateway, it does not work anymore ; I am still able to catch them manually, but they are not sent to front anymore.

Example of output in my terminal, that I was once able to catch/send as user-friendly error:

api         | Error: this is still thrown if caught manually
api         |     at /api/src/websocket/chat.service.ts:67:28
api         |     at processTicksAndRejections (node:internal/process/task_queues:95:5)
api         |     at ChatService.createRoom (/api/src/websocket/chat.service.ts:66:3)

CodePudding user response:

Without the await in the gateway call, the promise is not properly handled the the lifecycle of the request, as Nest sees it, ends, so when an error happens it is outside of the exception zone that Nest is responsible for. Add await to the this.chatService.createRoom(client, channel) and all should be good from there

  • Related