[英]How to get the exception error as Object in Nestjs Validation?
[英]How to use validation in NestJs with HTML rendering?
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)
添加到您的控制器或其方法來使用它。
另一種方法(作為一個新手,我發現更平易近人)是像這樣使用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"] })
}
}
然后,您可以將@UseFilters(new HttpExceptionFilter())
裝飾器添加到控制器方法中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.