NestJS管道抛出错误如何直接返回HTTP响应?
问题描述
在NestJS应用中实现了ValidUrlPipe用于校验URL合法性,管道抛出BadRequestException时,接口却返回500内部服务器错误,无法直接返回带提示的HTTP响应。
管道代码:
import { BadRequestException, Injectable, PipeTransform } from '@nestjs/common'; @Injectable() export class ValidUrlPipe implements PipeTransform { transform(website: string) { if (website === '') return website; const validProtocols = ['http:', 'https:']; const { protocol } = new URL(website); if (validProtocols.includes(protocol)) { return website; } throw new BadRequestException(`invalid website value: ${website}`); } }
控制器使用代码:
@Post() create( @Body('website', ValidUrlPipe) website: string, @Body() createTvDto: CreateTvDto, @CurrentUser() user: User, ) { return this.televisionsService.create(user._id, createTvDto); }
问题原因
当传入无效URL时,new URL(website)会直接抛出TypeError,这个错误没有被管道捕获,导致NestJS将其视为未处理的服务器错误,返回500状态码,而非预期的400错误。
解决方案
在管道的transform方法中,用try-catch包裹URL解析逻辑,捕获无效URL的错误并抛出BadRequestException:
import { BadRequestException, Injectable, PipeTransform } from '@nestjs/common'; @Injectable() export class ValidUrlPipe implements PipeTransform { transform(website: string) { if (website === '') return website; const validProtocols = ['http:', 'https:']; try { const { protocol } = new URL(website); if (validProtocols.includes(protocol)) { return website; } throw new BadRequestException(`invalid website value: ${website}`); } catch (error) { // 捕获URL解析失败的错误 throw new BadRequestException(`invalid website format: ${website}`); } } }
说明
修改后,无论URL格式错误还是协议不合法,都会抛出BadRequestException,NestJS会自动返回400状态码并携带自定义错误消息,无需查看服务器日志即可明确错误原因。
内容的提问来源于stack exchange,提问作者Dora
相关产品推荐
相关产品推荐

