Skip to content

WsException

reference
1 min readUpdated

Kind: Class

Source: packages/websockets/errors/ws-exception.ts

Part of: Websockets

WsException represents an error that should be sent through the WebSocket error-handling flow. It accepts either a string or object payload, initializes a message for standard error reporting, and preserves the original error value for consumers that need structured details.

Extends: Error

Methods

MethodSignatureReturns
initMessageinitMessage()void
getErrorgetError()`string

Diagram

mermaid
graph LR
  A[WebSocket handler] --> B[new WsException(error)]
  B --> C[initMessage()]
  C --> D[Exception message]
  B --> E[getError()]
  E --> F[String or structured error payload]
  F --> G[WebSocket exception filter/client response]

Usage

ts
import { WsException } from '@nestjs/websockets';

function handleSubscribe(topic?: string) {
  if (!topic) {
    throw new WsException({
      status: 'error',
      code: 'TOPIC_REQUIRED',
      message: 'A subscription topic is required.',
    });
  }

  return { status: 'ok', topic };
}

// The original payload remains available when handling the exception.
const exception = new WsException('Subscription failed');

console.log(exception.message); // "Subscription failed"
console.log(exception.getError()); // "Subscription failed"

AI Coding Instructions

  • Throw WsException from WebSocket handlers when an error should be delivered through the WebSocket exception pipeline.
  • Pass a string for simple client-facing errors; pass an object when clients need structured fields such as code, status, or validation details.
  • Use getError() when writing exception filters or adapters that must access the original error payload.
  • Do not assume getError() always returns a string; handle both string and object values safely.
  • Keep error payloads serializable and avoid including internal stack traces or sensitive server details.

How it works

WsException

WsException is an Error subclass that carries a WebSocket error value as either a string or an object. Its constructor stores that value in a private, readonly error field, calls Error’s no-argument constructor, and initializes the inherited message property. [packages/websockets/errors/ws-exception.ts:3-7]

Relationships

  • IMPORTS → isObject
  • IMPORTS → isString

Used by

3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example.

Imported by (3)

  • ApplicationGatewayintegration/websockets/src/app.gateway.ts:12
  • ErrorGatewayintegration/websockets/src/error.gateway.ts:8
  • RequestFilterintegration/websockets/src/request.filter.ts:4

Was this page helpful?

Download as PDF
WsException — NestJS head-to-head