@nestjs/websockets
Version:
WebSockets for NestJS: gateways with message handlers, guards, pipes and interceptors, on Socket.IO or ws.
48 lines (47 loc) • 1.69 kB
JavaScript
import { BaseWsExceptionFilter } from './base-ws-exception-filter.js';
import { selectExceptionFilterMetadata, isEmptyArray, isFunction, } from '@nestjs/common/internal';
import { InvalidExceptionFilterException } from '@nestjs/core/internal';
/**
* @publicApi
*/
export class WsExceptionsHandler extends BaseWsExceptionFilter {
filters = [];
// The promises of asynchronous filters, for handle() to return
pendingFilterResults = new WeakMap();
/**
* Returns the promise of an asynchronous exception filter. The exception is
* being handled until it settles, so callers wait for it: the adapters
* count the message as being handled until then.
*/
handle(exception, host) {
const client = host.switchToWs().getClient();
if (this.invokeCustomFilters(exception, host)) {
const pending = this.pendingFilterResults.get(host);
this.pendingFilterResults.delete(host);
return pending;
}
if (!client) {
return;
}
super.catch(exception, host);
}
setCustomFilters(filters) {
if (!Array.isArray(filters)) {
throw new InvalidExceptionFilterException();
}
this.filters = filters;
}
invokeCustomFilters(exception, args) {
if (isEmptyArray(this.filters))
return false;
const filter = selectExceptionFilterMetadata(this.filters, exception);
if (!filter) {
return false;
}
const result = filter.func(exception, args);
if (isFunction(result?.then)) {
this.pendingFilterResults.set(args, result);
}
return true;
}
}