Home > Back-end >  can't set status of 400 in express
can't set status of 400 in express

Time:05-05

I have a simple web service and it has a route for register user ,

I want when email exists in DB throw an error with status of 400 or other

I've done it like this

controllers/user.js

const { User } = require('../models/user')

exports.create = async (req, res) => {
    try {
        const { email } = req.body
        const user = await User.findOne({ email })
        if (user) {
            return res.json({ err: 'email already exists' })
        }
        await User.userValidation(req.body)
        await User.create(req.body)
        return res.json({})
    } catch (err) {
        res.status(400).send({ err })
    }

}

BUT , it always give status of 200,

where is the problem ?

CodePudding user response:

Add the status to your response:

 if (user) {
    return res.status(400).json({ err: 'email already exists' })
 }

CodePudding user response:

You can simply send the status 400 when checking if(user)

if(user){
    res.status(400).jsom({ err: "Email already exists" });
}

OR Threat the errors and add a middleware using next (a little bit more complicated then the first one, but more proffessional)

exports.create = async (req, res, next) => {
    try {
        const { email } = req.body
        const user = await User.findOne({ email })
        if (user) {
            throw new Error("Email already exists");
        }
        await User.userValidation(req.body)
        await User.create(req.body)
        return res.json({})
    } catch (err) {
        next(err, req, res, next);
    }

}

In the next middleware you can threat the error and send whatever response you need. (err, req, res objects are sent like references, so you can use them there)

  • Related