1

I'm using Reactjs web application. There I'm calling Nodejs RestAPI.

When API returns status code 400, I can't get it error message which is coming from API.

I'm not able to get the errorDesc from API response.

400 error API response

{
  "errorCode": "M400",
  "message": "Invalid Request",
  "errorDesc": "missing required first name field"
}

React code:

fetch(URL, {
            method: 'POST',
            body: data
        })
            .then(response => {
                if (!response.ok) {
                    if (response.status == 400) {
                        Modal.error({
                            className: "ErrorModal",
                            title: "Error",
                            content: "Invalid Request.",
                        });
                    }
                    return Promise.reject(response.statusText);
                }
                return response.json();
            })
            .then(status => {
                
            })
            .catch(error => {
                console.log(error);
            });
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Maria Jeysingh Anbu
  • 3,164
  • 3
  • 34
  • 55

1 Answers1

1

To get the content of the error response, you need to read the body of the response.

it might not be json, but if you happen to know it is, you would just use response.json() just like you do for the actual valid result.

Or, use response.text() to get the text version, which you can still parse as json afterwards if you want.

One possible approach

fetch(URL, {
            method: 'POST',
            body: data
        })
            .then(response => {
                if (!response.ok) {
                    if (response.status == 400) {
                      return response.json().then((error) => {
                      
                        Modal.error({
                            className: "ErrorModal",
                            title: error.message || 'Invalid Request',
                            content: error.errorDesc || '',
                        });
                        return Promise.reject(response.statusText);
                      });
                    } else {
                      return Promise.reject(response.statusText);
                    }
                }
                return response.json();
            })
            .catch(error => {
                console.log(error);
            });
Garr Godfrey
  • 8,257
  • 2
  • 25
  • 23