简体   繁体   English

如何在带有 HTML 渲染的 NestJs 中使用验证?

[英]How to use validation in NestJs with HTML rendering?

NestJS uses validation with validation pipes and NestJS 使用带有验证管道的验证和

@UsePipes(ValidationPipe)

If this fails it throws an exception.如果失败,它会抛出异常。 This is fine for REST APIs that return JSON.这适用于返回 JSON 的 REST API。

How would one validate parameters when using HTML rendering and return使用 HTML 渲染和返回时如何验证参数

{ errors: ['First error'] }

to an hbs template?到 hbs 模板?

You can create an Interceptor that transforms the validation error into an error response:您可以创建一个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]}),
      ),
    );
  }
}

You can use it by adding @UseInterceptors(ErrorsInterceptor) to your controller or its methods.您可以通过将@UseInterceptors(ErrorsInterceptor)添加到您的控制器或其方法来使用它。

Another approach (which as a newcomer, I find more approachable) is to use ExceptionFilter s like so:另一种方法(作为一个新手,我发现更平易近人)是像这样使用ExceptionFilter

import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const exceptionResponse = exception.getResponse()

    response.render(YOUR_TEMPLATE_HERE, { errors: exceptionResponse["message"] })
  }
}

You can then add the @UseFilters(new HttpExceptionFilter()) decorator to the controller method.然后,您可以将@UseFilters(new HttpExceptionFilter())装饰器添加到控制器方法中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM