Kind: Class
Source: packages/websockets/exceptions/base-ws-exception-filter.ts
Part of: Websockets
BaseWsExceptionFilter is the default foundation for handling exceptions thrown during WebSocket message processing. It distinguishes WsException instances from unknown errors, emits structured error payloads to the connected client, and provides safe fallback handling for unexpected failures.
Implements: WsExceptionFilter
Methods
| Method | Signature | Returns |
|---|---|---|
catch | catch(exception: TError, host: ArgumentsHost) | void |
handleError | handleError(client: TClient, exception: TError, cause: ErrorPayload['cause']) | void |
handleUnknownError | handleUnknownError(exception: TError, client: TClient, data: ErrorPayload['cause']) | void |
isExceptionObject | isExceptionObject(err: any) | err is Error |
Properties
| Property | Type |
|---|---|
logger | any |
Where it refuses work
BaseWsExceptionFilterstops the work with an early return when!(exception instanceof WsException).BaseWsExceptionFilterstops the work with an early return whenisObject(result).
Diagram
mermaidgraph LR A[WebSocket handler throws error] --> B[BaseWsExceptionFilter.catch] B --> C{Is WsException?} C -->|Yes| D[handleError] C -->|No| E[handleUnknownError] D --> F[Emit exception event to client] E --> G[Create generic error payload] G --> F
Usage
tsimport { Catch, WsException } from '@nestjs/common';
import { BaseWsExceptionFilter } from '@nestjs/websockets';
import type { ArgumentsHost } from '@nestjs/common';
@Catch()
export class GatewayExceptionFilter extends BaseWsExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
// Add application-specific logging or monitoring here.
console.error('WebSocket exception:', exception);
// Delegate standard client error handling to the base filter.
super.catch(exception, host);
}
}
// In a gateway:
import { UseFilters, SubscribeMessage, WebSocketGateway } from '@nestjs/websockets';
@WebSocketGateway()
@UseFilters(new GatewayExceptionFilter())
export class EventsGateway {
@SubscribeMessage('create-event')
createEvent() {
throw new WsException({
code: 'EVENT_CREATION_FAILED',
message: 'Unable to create the event.',
});
}
}
AI Coding Instructions
- Extend
BaseWsExceptionFilterwhen custom logging, metrics, or error transformation is needed; callsuper.catch()to preserve standard WebSocket error delivery. - Throw
WsExceptionfor expected client-facing failures sohandleError()can emit the intended error payload. - Do not expose stack traces, database details, or internal exception messages through unknown-error responses.
- Ensure filters are registered with
@UseFilters()on the gateway, controller, or individual message handler as appropriate. - Remember that errors are emitted to the WebSocket client through the
exceptionevent rather than returned as HTTP responses.
Was this page helpful?