Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read 400 or 500 JSON response

I have a Nodejs server running that registers the users. On successful registration, it returns a status code of 200 and a JSON response. But on unsuccessful registration where the email already exists, it returns the status code of 400 and a JSON response.
Now the problem is that I’m able to read the JSON of 200 responses but I’m not able to access the JSON of 400 responses. I am using axios to fetch the data from the server.

Code for the email that already exists

if (emailExists) {
      return res.status(400).json({
        success: false,
        message: 'This email address is already being used.'
      })
    }

Response for a valid registration

return res.status(200).json({
      success: true,
      message: 'You are signed up successfully.',

    })

Response on successful signup
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Behaviour when the email is already being used
enter image description here

This is how I’m sending the request
enter image description here

>Solution :

With axios(), to handle a 400 error, you need to use a .catch() to catch the rejected promise and then examine the error object you get. So, in addition to your .then(), use a .catch():

axios(...).then((result) => {
   console.log(result);
}).catch(err => {
    console.log(err.response.status);
    console.log(err.response.data);
});

Or, if you were using an await fetch(...), then surround that with a try/catch and catch the error in the catch block.

In your code ALL promises that can ever reject MUST have an error handler for the rejection. Since your console shows "uncaught (in promise) Error", that means you had no means of catching the rejected promise.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading