Issue
I have my system that has custom errors like this:
import { ExtendableError } from './extandable.error'
export const customError = {
EMAIL_EXIST: () => new ExtendableError({
message: 'USER WITH SUCH EMAIL ALREADY EXIST',
code: 403
}),
INVALID_EMAIL: () => new ExtendableError({
message: 'INVALID EMAIL',
code: 400
}),
INVALID_PASSWORD: () => new ExtendableError({
message: 'INVALID EMAIL OR PASSWORD',
code: 403
}),
EMAIL_DOES_NOT_EXIST: () => new ExtendableError({
message: 'EMAIL DOES NOT EXIST',
code: 404
}),
TOKEN_DOES_NOT_EXIST: () => new ExtendableError({
message: 'TOKEN DOES NOT EXIST',
code: 404
}),
DIFFERENT_PASSWORDS: () => new ExtendableError({
message: 'PASSWORDS ARE NOT SAME',
code: 400
}),
CURRENT_PASSWORD_ERR0R: () => new ExtendableError({
message: 'CURRENT PASSWORD IS INCORRECT',
code: 400
}),
SAME_PASSWORDS_ERROR: () => new ExtendableError({
message: 'CANNOT CHANGE SET NEW PASSWORD AS OLD PASSWORD',
code: 403
})
}
Here I can write my own error responses When I request something, and for example emails exists, it throws an error that such email while registration already exists.
It states here:
async createAccount (doc: RegisterDto, verificationLink: string) {
if (!isValidEmail(doc.email)) {
return customError.INVALID_EMAIL()
}
const user = await this.existByEmail(doc.email)
if (!user) {
return customError.EMAIL_EXIST()
}// HERE I RETURNING AN ERROR TO CONTROLLER
doc.password = await bcrypt.hash(doc.password, SALT_ROUNDS)
const created = await this.repository.create(this.registerMapper.toDomain(doc))
await this.emailService.sendVerificationEmail(created, verificationLink)
return created
}
Here is my function in controller:
@Post('/api/register')
async register(@Body() registerDTO: RegisterDto, @Request() request, @Response() response) {
const verificationLink = `${request.protocol}://${request.header.host}/api/verify-account/`
return await this.service.createAccount(registerDTO, verificationLink)
}
In postman, it shows me the body and the response, but the actual result of the status code has 201 code
How can I fix it?

Solution
Instead of return customError.INVALID_EMAIL() you should throw an error.
From npm docs:
let ExtendableError = require('extendable-error');
class MyCustomError extends ExtendableError {};
throw new MyCustomError('A custom error ocurred!');
Answered By - Chai
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.