In my NestJS application, I have created a custom pipe that validates if a given value is a valid URL. If the URL is invalid, an error is thrown. This pipe is utilized in a controller to save an item into the database.
Recently, I discovered that the pipe was returning a 500 Internal Server Error response, prompting me to check the server logs to confirm if it originated from the pipe itself.
I am curious if there is a way to generate an HTTP response directly with a specific message instead of just throwing an error?
The code snippet for the pipe implementation:
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}`);
}
}
Here's how the controller utilizes the pipe:
@Post()
create(
@Body('website', ValidUrlPipe) website: string,
@Body() createTvDto: CreateTvDto,
@CurrentUser() user: User,
) {
return this.televisionsService.create(user._id, createTvDto);
}
Appreciate any suggestions or solutions you may have regarding this issue. Thank you in advance!
https://i.stack.imgur.com/zQPMr.png
EDIT: Added an image showing the error received when using Postman to call the endpoint