Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

220
Vistas
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 Respuestas
Responde la pregunta

0

Add the status to your response:

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

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda