Geo*_*tan 4 websocket node.js nestjs
我有以下示例:
@SubscribeMessage('v1-test')
@UsePipes(ValidationPipe)
@UseFilters(ValidationOnSocketExceptionFilter)
async test(
@MessageBody() payload: payloadDTO,
@ConnectedSocket() client: Socket,
){
.....do stuff......
return true;
}
Run Code Online (Sandbox Code Playgroud)
这是 ValidationOnSocketExceptionFilter:
@Catch(BadRequestException)
export class ValidationOnSocketExceptionFilter
implements ExceptionFilter<BadRequestException> {
private readonly logger = new Logger(ValidationOnSocketExceptionFilter.name);
constructor(private readonly customResponseService: CustomResponseService) {}
catch(exception: BadRequestException, host: ArgumentsHost) {
console.log('Validation err on socket');
const client = host.switchToWs().getClient();
// * get the msg from all validation erros
let constraints: string[] | string;
if (typeof exception.getResponse() === 'object') {
let err: any = exception.getResponse();
if (err.message && Array.isArray(err.message)) constraints = err.message;
} else {
constraints = exception.getResponse() as string;
}
const err: CustomResponse = this.customResponseService.buildErrorResponse(
ErrCodes.BAD_PARAMETERS,
constraints,
);
console.log(client);
client.emit(SocketMessages.CustomError, err);
}
}
Run Code Online (Sandbox Code Playgroud)
我想要做的不是使用client.emit(SocketMessages.CustomError, err);创建和发送新事件 ,而是简单地使用return err,这意味着我想使用确认函数返回错误,就像我在函数test()中所做的那样
小智 7
您可以通过 中的第三个参数获取回调函数ArgumentsHost。
catch(exception: BadRequestException, host: ArgumentsHost) {
// ...
const err: CustomResponse = this.customResponseService.buildErrorResponse(
ErrCodes.BAD_PARAMETERS,
constraints,
);
const callback = host.getArgByIndex(2);
if (callback && typeof callback === 'function') {
callback(err);
}
}
Run Code Online (Sandbox Code Playgroud)
仅测试了@nestjs/platform-socket.io.