gpt4 book ai didi

node.js - NestJS - 在异常过滤器中返回 ACK

转载 作者:行者123 更新时间:2023-12-04 10:01:39 28 4
gpt4 key购买 nike

我有以下示例:

@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 进行测试。

关于node.js - NestJS - 在异常过滤器中返回 ACK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61795299/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com