Exception filters

The only difference between the HTTP exception filter layer and the corresponding web sockets layer is that instead of throwing HttpException, you should use WsException.

  1. throw new WsException('Invalid credentials.');

info Hint The WsException class is imported from the @nestjs/websockets package.

With the sample above, Nest will handle the thrown exception and emit the exception message with the following structure:

  1. {
  2. status: 'error',
  3. message: 'Invalid credentials.'
  4. }

Filters

Web sockets exception filters behave equivalently to HTTP exception filters. The following example uses a manually instantiated method-scoped filter. Just as with HTTP based applications, you can also use gateway-scoped filters (i.e., prefix the gateway class with a @UseFilters() decorator).

  1. @UseFilters(new WsExceptionFilter())
  2. @SubscribeMessage('events')
  3. onEvent(client, data: any): WsResponse<any> {
  4. const event = 'events';
  5. return { event, data };
  6. }

Inheritance

Typically, you’ll create fully customized exception filters crafted to fulfill your application requirements. However, there might be use-cases when you would like to simply extend the core exception filter, and override the behavior based on certain factors.

In order to delegate exception processing to the base filter, you need to extend BaseWsExceptionFilter and call the inherited catch() method.

  1. @@filename()
  2. import { Catch, ArgumentsHost } from '@nestjs/common';
  3. import { BaseWsExceptionFilter } from '@nestjs/websockets';
  4. @Catch()
  5. export class AllExceptionsFilter extends BaseWsExceptionFilter {
  6. catch(exception: unknown, host: ArgumentsHost) {
  7. super.catch(exception, host);
  8. }
  9. }
  10. @@switch
  11. import { Catch } from '@nestjs/common';
  12. import { BaseWsExceptionFilter } from '@nestjs/websockets';
  13. @Catch()
  14. export class AllExceptionsFilter extends BaseWsExceptionFilter {
  15. catch(exception, host) {
  16. super.catch(exception, host);
  17. }
  18. }

The above implementation is just a shell demonstrating the approach. Your implementation of the extended exception filter would include your tailored business logic (e.g., handling various conditions).