# WsExceptionFilter

**Kind:** Interface

**Source:** [`packages/common/interfaces/exceptions/ws-exception-filter.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/exceptions/ws-exception-filter.interface.ts#L11)

**Part of:** [Common](subsystem-packages-common)

Interface describing implementation of a Web Sockets exception filter.

`WsExceptionFilter` defines the contract for handling exceptions thrown during WebSocket message processing. Implementations receive the thrown exception and the current `ArgumentsHost`, allowing them to inspect the WebSocket client, request data, and emit an appropriate error response. Use this interface when creating custom filters for WebSocket gateways.

## Diagram

```mermaid
graph LR
  A[WebSocket Client Event] --> B[Gateway Handler]
  B -->|Throws exception| C[WsExceptionFilter.catch]
  C --> D[ArgumentsHost]
  D --> E[WebSocket Client]
  C --> F[Emit or return error response]
  F --> E
```

## Usage

```ts
import {
  ArgumentsHost,
  Catch,
  UseFilters,
  WsException,
  WsExceptionFilter,
  WebSocketGateway,
  SubscribeMessage,
} from '@nestjs/common';

@Catch(WsException)
export class ChatWsExceptionFilter implements WsExceptionFilter {
  catch(exception: WsException, host: ArgumentsHost) {
    const client = host.switchToWs().getClient();
    const error = exception.getError();

    client.emit('exception', {
      status: 'error',
      message: typeof error === 'string' ? error : 'Unable to process message',
    });
  }
}

@WebSocketGateway()
@UseFilters(new ChatWsExceptionFilter())
export class ChatGateway {
  @SubscribeMessage('send-message')
  sendMessage() {
    throw new WsException('Message delivery failed');
  }
}
```

## AI Coding Instructions

- Implement a `catch(exception, host)` method that matches the `WsExceptionFilter` contract.
- Use `host.switchToWs()` to access the WebSocket client and incoming message data.
- Prefer handling `WsException` explicitly and safely normalize its error payload before sending it to clients.
- Emit a consistent error event, such as `exception`, so WebSocket clients can handle failures predictably.
- Register filters with `@UseFilters()` on a gateway or individual message handler as needed.

## Used by

1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example.

### Imported by (1)

- `ErrorPayload` — `packages/websockets/exceptions/base-ws-exception-filter.ts`:11
