NestJS使用验证管道和验证
@UsePipes(ValidationPipe)
如果失败则抛出异常。这适用于返回JSON的REST API。
在使用HTML呈现和返回时,如何验证参数
{ errors: ['First error'] }
到一个HBS模板?
您可以创建一个Interceptor
,将验证错误转换为错误响应:
@Injectable()
export class ErrorsInterceptor implements NestInterceptor {
intercept(
context: ExecutionContext,
call$: Observable<any>,
): Observable<any> {
return call$.pipe(
// Here you can map (or rethrow) errors
catchError(err => ({errors: [err.message]}),
),
);
}
}
您可以通过将@UseInterceptors(ErrorsInterceptor)
添加到控制器或其方法来使用它。