Exception filters

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

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

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

Nest will handle thrown exception and as a result, emits the exception message with the following structure:

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

Filters

The custom filters feature is supported as well and works equivalently. Here is an example that makes use of a manually instantiated method-scope filter (class-scoped works too):

  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. There might be use-cases though when you would like to reuse an already implemented, 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 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. }

Obviously, you should enhance above implementation with your tailored business logic (e.g. add various conditions).