Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
can't set status of 400 in express

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 ?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Add the status to your response:

 if (user) {
    return res.status(400).json({ err: 'email already exists' })
 }
over 4 years ago · Santiago Trujillo Report

0

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)

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!