Reputation: 35
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?
Upvotes: 1
Views: 3981
Reputation: 832
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)}
Upvotes: 5
Reputation: 1
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 :)
Upvotes: 0
Reputation: 373
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,
});
}
};
Upvotes: -1
Reputation: 1874
Try this:
.catch((err) => {
console.log(err.response); // err.response.status will give you the error code.
})
Upvotes: 2
Reputation: 351
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')
Upvotes: -1