1
votes

I am making a save operation that when the data is invalid the response is a 400 HTTP status with the details in the JSON body. I want to read the JSON so I can display it below is the code I have been using but nothing seems to work on getting a 400 error body response

  private _onSave() {
    let e: EmployeeSaveEntity = this.state.employeeSave;
    this._save(e, this._onResponse.bind(this) , this._onCheckError.bind(this));  
  }

  public _save(employee: EmployeeSaveEntity, onFulfilled: any, onReject: any) {
    let url: string = __URL__;
    url += 'Employees';

    let context: any = this;
    let res: Promise<Response>;
    try {
        res = fetch(url,
            {   
                //"cors" | "navigate" | "same-origin" | "no-cors"
                //mode:"no-cors",
                method: "POST",
                headers: {
                    'Authorization': `Bearer ${context._authentication.token.access_token}`,
                    "Content-Type": "application/json"
                },
                body: employee.getJSON()
            }).then(onFulfilled, onReject);
        }
        catch (error) {
            throw new Error('Failed to save employee');
        };
}

  private _onCheckError(value: any) {
    console.log('_onCheckError');
    console.log(value);
  }

  private _onResponse(value: Response) {    
    console.log('_onResponse');
    console.log(value);
    console.log( value.text() );
    value.json().then(this._onJson.bind(this), this._onCheckError.bind(this));
  }
  private _onJson(value: any) {

    console.log('_onJson');
    console.log(value);
  }

HTTP/1.1 400 Bad Request Cache-Control: no-cache Pragma: no-cache Transfer-Encoding: chunked Content-Type: application/json; charset=utf-8 Expires: -1 Date: Fri, 20 Oct 2017 14:50:33 GMT X-Response-From: 10.50.46.29

{"HierId":[ "You can not insert master table data into the system at this hierarchy level." ], "PrimaryPhoneNumberCountryCallingCode":[ "The PrimaryPhoneNumberCountryCallingCode is required when PrimaryPhoneNumber has a value." ] }

1
You aren't sending content-length in your headers. That may be an issue. From the RFC, "Applications SHOULD use this field to indicate the transfer-length of the message-body, unless this is prohibited by the rules in section 4.4." - Alex W
application/json does not have a charset. - Antti Haapala
The content-length is not needed the fetch appends it to the header. This all works when the data is correct I get a response 200 back an everything works. What I really want to know is how do you read the body of a Bad Request. - user1730289

1 Answers

0
votes

Since the HTTP request was successful (you got any response) then the result will just be passed to onFulfilled method.

Look at this example:

fetch("/error").then((response) => { 
    console.log(response.status);  //400 in your case
    response.json().then((errorJson) => {
        console.log(errorJson); // should return the error json
    }); 
})