Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

229
Visualizações
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 Respostas
Responde à pergunta

0

Add the status to your response:

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

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda