如何在NestJS中自定义ParseUUIDPipe的错误提示信息?
自定义NestJS ParseUUIDPipe错误提示
当然可以自定义错误提示信息,以下是两种实用方案:
1. 直接在Pipe实例中配置
在实例化ParseUUIDPipe时,通过exceptionFactory选项返回自定义异常,传入友好提示:
@Get(':id') async getItem( @Param('id', new ParseUUIDPipe({ version: '4', exceptionFactory: () => new BadRequestException('请传入有效的UUID v4格式参数') })) id: string, @GetAccount() acct: AccountEntity, ): Promise<ItemEntity> { return this.itemService.getItem(id, acct); }
exceptionFactory是一个返回HttpException类型的函数,你可以根据需求选择合适的异常类型(比如BadRequestException),并自定义提示文本。
2. 创建自定义Pipe实现全局复用
如果多个地方需要统一的错误提示,可以创建自定义Pipe继承ParseUUIDPipe,重写异常处理逻辑:
import { ParseUUIDPipe, BadRequestException, HttpException } from '@nestjs/common'; export class CustomParseUUIDPipe extends ParseUUIDPipe { constructor(options?: { version?: '3' | '4' | '5' | 'all' }) { super(options); } protected exceptionFactory(error: string): HttpException { return new BadRequestException('请传入符合要求的UUID格式参数'); } }
之后在控制器中直接使用自定义Pipe:
@Get(':id') async getItem( @Param('id', new CustomParseUUIDPipe({ version: '4' })) id: string, @GetAccount() acct: AccountEntity, ): Promise<ItemEntity> { return this.itemService.getItem(id, acct); }
内容的提问来源于stack exchange,提问作者Chris Barr
相关产品推荐
相关产品推荐

