1

I am currently developing a RESTful API with the help of Node.js and a client with React.

I am at the very beginning, ie the creation of a user via a registration form, and I realized that I do not really know how to handle the errors that my API sends me with React.

For example if I want to register with a username that is already taken, the controller of my API will throw an error :

throw {status: 422, message: "Username already used"}

My React client will retrieve it and display it in the console at the moment, but it displays a very general error (Request failed with status code 422) and not the message "Username already used"

_addUser(username, email, password)
 .then((res) => {
   console.log(res);
 })
 .catch((err) => {console.log(err.message)})

Does anyone have an idea of ​​how to solve my problem? Or another way to handle errors?

4
  • 1
    Errors like the one you are describing are valid responses. You should check the status code and then change React state so that you can render a nice message for your user. Commented Jul 22, 2019 at 16:00
  • @DavinTryon how can I check the status code in my React app ? Commented Jul 22, 2019 at 16:30
  • it depends what http library you are using. looks like it should be at res.status. Commented Jul 22, 2019 at 16:39
  • i'm using express, if i console.log res.status in the .catch the value is undefined Commented Jul 22, 2019 at 16:49

5 Answers 5

5

Your Backend Node.js code:

return res.status(500).json({message: "Email already registered"})

Your Frontend React or React Native code:

try{// some code}
catch (error){
   console.log(error.response.data.message)}
Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

.catch((err) => {
    console.log(err.response); // err.response.status will give you the error code.
})

Comments

0

This is late, but I figured out why your custom error isn't showing. In your catch block, instead of console logging:

err.message

Try logging:

err.**response**

Look at this in your console and display accordingly :)

Comments

-1

You should throw error with the new keyword. Then you should be able to display the message.

throw new Error('Username already used')

Or if you are using express, you can go like this:

res.status(422).send('Username already used')

6 Comments

I'm getting "Error: Request failed with status code 500" using this, still not my custom error message :/
I'm using Express but your second suggestion is still not giving me my custom message
Then you can check for the status code, 422 in your case, and display error message in your React application based on this code.
But how can i get the status code in my React app ?
@Paul28000 what does you console.log(err) display?
|
-1
Please refer a below link:
https://medium.com/@chiragpatel.cmpicamsit15/error-handling-from-express-js-node-js-to-react-axios-error-handling-7758de90d365

**Server Side Node Js Code :**

   module.exports = (app) => {
app.put(‘/updateUser’, (req, res, next) => {
passport.authenticate(‘jwt’, { session: false }, (err, user, info) => {
if (err) {
console.error(err);
}
if (info !== undefined) {
console.error(info.message);
res.status(403).send(info.message);
} else {
User.findOne({
where: {
username: req.body.username,
},
}).then((userInfo) => {
if (userInfo != null) {
console.log(‘user found in db’);
userInfo
.update({
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
})
.then(() => {
console.log(‘user updated’);
res.status(200).send({ auth: true, message: ‘user updated’ });
});
} else {
console.error(‘no user exists in db to update’);
res.status(401).send(‘no user exists in db to update’);
}
});
}
})(req, res, next);
});
};


**Client-Side (React JS) :**


updateUser = async (e) => {
const accessString = localStorage.getItem(‘JWT’);
if (accessString === null) {
this.setState({
loadingUser: false,
error: true,
});
}
const {
first_name, last_name, email, username
} = this.state;
e.preventDefault();
try {
const response = await axios.put(
‘http://localhost:3003/updateUser’,
{
first_name,
last_name,
email,
username,
},
{
headers: { Authorization: `JWT ${accessString}` },
},
);
// eslint-disable-next-line no-unused-vars
console.log(response.data);
this.setState({
updated: true,
error: false,
});
} catch (error) {
console.log(error.response.data);
this.setState({
loadingUser: false,
error: true,
});
}
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.