TheStuntback46
TheStuntback46

Reputation: 47

How can you explain that weird behavior on Http Error message with Node.js

I have made an Api with Node.js but I have some weird behaviour with my error handling. You can see the code below. I'm checking a form with node.js if the form is not valid I'm sending back to the frontend an error message. I can get it(error 400 and 409) from the frontend on error.response.data.message(catch).

After I'm making an API call with axios if we cannot find the information sent by the user I return an error on the same way than before, but that time on the frontend I get it on error.response.data.response.data.message(the error 404).

So to receive it on error.response.data.message, I have to send the error like that this time: error.message.

So it is working but I just would like to understand what happens exactly.

Thanks in advance for your help!!!!!!

let error={response:{data:{message:"Thanks to fill properly all 
fields!!"}}}
if (formValid.length>0){  res.status(400).send(error);}
else{ 

    axios.get('https://someapi',{headers: 
    {
    "Authorization" : "XXXXXXX"
    }
    })
    .then(response => {
    var newUser = new User({username:req.body.username....});
    User.register(newUser,req.body.password, function(err, user){
    if(err){
       res.status(409).send(err);
    }
    else{ 
    res.status(200).send();
    }  

    })
    }).catch(e => {
    error={response:{data:{message:"The information you sent seem 
    wrong please check it again...}}}

    res.status(404).send(error);
    })}
}

Upvotes: 0

Views: 108

Answers (1)

Pranil Tunga
Pranil Tunga

Reputation: 76

Exactly if you observe the above error by logging it to the console you will see that it contains the message property in it direcly and that message property is binded to the data property of response but in below case you are passing the nested javascript object to error property which again adds the response property in error object so you need to access that message through error.response.data. response..... So in this scenario the whole javascript object is added to data property which causes that result.

Upvotes: 1

Related Questions