javascript - How to handle Node.js API errors with React - Stack Overflow

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

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?

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?

Share Improve this question asked Jul 22, 2019 at 15:45 Paul28000Paul28000 351 silver badge7 bronze badges 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. – Davin Tryon Commented Jul 22, 2019 at 16:00
  • @DavinTryon how can I check the status code in my React app ? – Paul28000 Commented Jul 22, 2019 at 16:30
  • it depends what http library you are using. looks like it should be at res.status. – Davin Tryon Commented Jul 22, 2019 at 16:39
  • i'm using express, if i console.log res.status in the .catch the value is undefined – Paul28000 Commented Jul 22, 2019 at 16:49
Add a ment  | 

5 Answers 5

Reset to default 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)}

Try this:

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

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 :)

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')
Please refer a below link:
https://medium./@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,
});
}
};

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745437910a4627694.html

相关推荐

  • javascript - How to handle Node.js API errors with React - Stack Overflow

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

    15小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信