I am using NestJS as a backend framework and when doing Login service it is not returning a valid HTTP code. I used GlobalPipes on the app as it will be shown in the code provided. Also, the part of the code that is sending the error message is being activated and it sends the error message I put there but still the response has a bad code.
This is login code
async login(dto: LoginDto) {
try {
const user = await this.prisma.user.findUnique({
where: {
email: dto.email,
},
});
if (!user) throw new ForbiddenException('Credentials incorrect');
const pwMatches = await argon.verify(user.password, dto.password);
if (!pwMatches) throw new ForbiddenException('Credentials incorrect');
return this.signToken(user.id, user.email);
} catch (error) {
return error;
}
}
I encountered a similar issue, stumbled upon your question, and realized what might be happening. The problem lies in your return of an error object, which leads NestJS to serialize it and return an HTTP status of 201 for POST requests.
When an exception is raised, whether by your code or more likely by the ORM, you will immediately enter the catch block. To address this, you should throw an exception within the catch block to properly propagate the ForbiddenException to the controller, rather than returning the error object.
async login(dto: LoginDto) {
try {
const user = await this.prisma.user.findUnique({
where: {
email: dto.email,
},
});
if (!user) return new ForbiddenException('Credentials incorrect');
const pwMatches = await argon.verify(user.password, dto.password);
if (!pwMatches) return new ForbiddenException('Credentials incorrect');
return this.signToken(user.id, user.email);
} catch (error) {
// put some logs here
// some error handling
throw InternalServerException(`Something went wrong: ${error}`)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With