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

286
Visualizações
Handling express error in Next.js with axios

Im building the login functionality for my application with an asynchronous call to my API. My issue is that even though express is throwing an error, .then() is still being run with the error and not the actual user and token response. I am not sure why the login function is not 'catching' the error and instead running the code inside .then().

My express function:

// express funciton to login a user
app.post('/api/users/login', (req, res) => {
  const { email, password } = req.body
  database.getUser(email, password, (error, user) => {
    console.log(error)
    if (error) {
      res.send({ error })

//errors are being handled here and are returned in the result of my 
frontend API call

      return
    }
    const token = jwt.generateToken({ userId: user.id, name: user.name, email: user.email })
    res.send({ token: token, user:user })
  })
})

//getUser function with mySQL query
function getUser(email, password, callback) {
  const query = `
      SELECT id, name, email, password
      FROM users
      WHERE email = ?
  `
  const params = [email]

  connection.query(query, params, (error, results, fields) => {
    if (!results || results.length === 0) {
      callback(Error("Email is incorrect"))
      return
    }

    const user = results[0]

    bcrypt.compare(password, user.password, (error, same) => {
      console.log(error)
      if (error) {
        callback(error)
        return
      }

      if (!same) {
        callback(Error("Password is incorrect"))
        return
      }

      callback(null, user)
    })
  })
}
exports.getUser = getUser

My login function in Next.js:

    const login = async ({ email, password }) => {
        return await axios.post('http://localhost:4200/api/users/login', {
            email: email,
            password: password
        })
            .then((result) => {

//when backend throws error, they are contained here as "result.error" still running these lines of code

                sessionStorage.setItem('token', result.data.token);
                axios.defaults.headers.common['Authorization'] = "Bearer " + result.data.token;
                console.log('user signed in');
            })
            .catch((err) => {

//want errors to be directed here instead so I can properly handle them within the UI

                console.error("Username or password is incorrect!!")
            })
    };

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Where you have .catch(error) will only error if there is an issue with the axios promise itself being able to complete.

In this case, the axios promise is completing correctly, however, you are then returned a valid error code for why the login cannot complete.

Therefore one approach would be within your .then(result) function to look for that type of result and do something.

So something like

.then((result) => {
 if (result.error) { ... return an error message to user ... } 
 else {
  sessionStorage.setItem('token', result.data.token);
  axios.defaults.headers.common['Authorization'] = "Bearer " + 
  result.data.token;
  console.log('user signed in');}
})
about 4 years ago · Juan Pablo Isaza 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