我正在使用管道进行请求验证。如果请求失败,我想重定向到一个页面但不想抛出错误。问题是,如何在验证中访问响应对象?
这是我的验证管道。
@Injectable()
export class ValidationPipe implements PipeTransform<any> {
async transform(value: any, { metatype }: ArgumentMetadata) {
if (!metatype || !this.toValidate(metatype)) {
return value;
}
const object = plainToClass(metatype, value);
const errors = await validate(object);
if (errors.length > 0) {
// in here i need to response with res.redirect('') function
throw new BadRequestException('Validation failed');
}
return value;
}
private toValidate(metatype: Function): boolean {
const types: Function[] = [String, Boolean, Number, Array, Object];
return !types.includes(metatype);
}
}
我需要访问 res.redirect() 函数而不是抛出异常
最佳答案
response
对象在 pipe
的上下文中不可用。您可以做的是 A) 使用 interceptor
代替或 B) 抛出异常并使用 filter
捕获这个特定的异常并重定向到正确的位置。
管道
仅用于验证或对象转换,因此会立即返回成功(带有可能转换的对象)或抛出有关转换/验证失败原因的错误。
关于node.js - NestJS 访问管道中的响应对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56629059/