Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to show error message in react js when http request send?

could you please tell me how to show error message in react js when http request send ?

I make a service in the nodejs where I am sending 400 status with error message . I want to show this error message on frontend.

app.get('/a',(req,res)=>{
    res.status(400).send({message:" some reason error message"})
})

Now I want to show this error message on frontend .on catch I will not get this message.

try {
            const r = await axios.get('http://localhost:3002/a');
} catch (e) {
            console.log('===============================================')
            console.log(e)
            console.log(e.data)
            hideLoading();
            setErrorMessage(e.message);
            showErrorPopUp();
        }

on catch i will not get this message.getting on stack of error [![enter image description here][1]][1]

enter image description here

like image 328
user944513 Avatar asked Aug 21 '19 02:08

user944513


People also ask

How do I get error message from api response in React?

Make the api call, the server (assuming you are also building the server) should check to see if the name and phone number already exist. If they already exist the server should return an error. In your react app catch the error after your API call and assign it to your state variable for error.

How do you show error messages?

In order to display error messages on forms, you need to consider the following four basic rules: The error message needs to be short and meaningful. The placement of the message needs to be associated with the field. The message style needs to be separated from the style of the field labels and instructions.


1 Answers

It's better to respond with a JSON in this particular case from the server:

app.get('/a',(req,res) => {
    res.status(400).json({message:"some reason error message"})
})

So in the client, you can read from error.response easily

try {
  const r = await axios.get('http://localhost:3002/a');
} catch (e) {
  if (e.response && e.response.data) {
    console.log(e.response.data.message) // some reason error message
  }
}

Read more about handling caught errors in axios here

like image 200
Suman Kundu Avatar answered Sep 28 '22 03:09

Suman Kundu