How to show error returned from backend in nodejs in React

Asked

Viewed 1,776 times

0

I have a problem showing the error message that came from the backend. I return in the backend:

res.status(400). send({error: "User already exists"});

already on the front I would like to display this message, instead of the default message that is shown:

Request failed with status code 400

how can I receive and show this message coming from backend?

front-end code:

try{
    //sucess
}catch(error){
    console.log(`$error`);
}
  • 1

    put in question the javascript code where it treats the return of backend

  • if possible, send the return of your Sponse -> console.log(Answer)

  • I believe you’re using Aces to make the request, right?

3 answers

1


try {
  // Faça aqui sua requisição
  const response = await http.get("http://exemplo")
} catch (error) {
  // Caso a requisição dentro do try falhe
  // este bloco captará o erro
  const mensagem = error.response.error 
  // Aqui você acessa o objeto que retornou do backend
  // Faça o que quiser com ele
}

0

You only need to read your Answer’s status property when it comes to receiving it on the front end

Depending on how you’re sending the information here’s an example of how you can do it.

  function(res){
      if(res.status > 302){
        console.log(res);
      }
  }

to do within a try catch you need to use the throw

-2

If you catch the error.

} catch(error) {
    setAuthenticated(false);
    const { data } = error.response;
    alert(data.message);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.