node.js - NestJS - 在异常过滤器中返回 ACK
问题描述
我有以下示例:
@SubscribeMessage('v1-test')
@UsePipes(ValidationPipe)
@UseFilters(ValidationOnSocketExceptionFilter)
async test(
@MessageBody() payload: payloadDTO,
@ConnectedSocket() client: Socket,
){
.....do stuff......
return true;
}
这是 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);
}
}
我想要做的不是使用client.emit(SocketMessages.CustomError, err); 创建和发送新事件;,而是简单地使用return err,这意味着我想使用确认函数返回错误,就像我在函数test()中所做的一样
解决方案
您可以通过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);
}
}
仅使用@nestjs/platform-socket.io
.
推荐阅读
- html - 交换字体时的字体转换
- python - 如何通过生命周期配置使用 boto3 更改 S3 存储桶文件夹中所有对象的存储类?
- kubernetes - 无法通过 macvlan 访问不同工作人员(节点)中的 pod
- r - oath_listener() 需要一个交互式环境
- python - 在 python 列表中打印特定项目
- javascript - 将动态类型分配给字符串
- jquery - 悬停时如何为引导卡设置动画?
- service-worker - 如何在用户脚本中使用服务工作者
- wordpress - 让 Apache 2.4 和 mod_authn_dbd 与 Wordpress 用户数据库一起工作
- android-studio - Android Studio 行为不稳定且未成功构建