1

I'm pretty new to the fetch api and cant figure out why I can access response.json() locally but not once deployed.

EDIT: Just making the question clearer. When my response is NOT ok, I want to send response.json() to my errorCallBack function. This works locally and I set my error message to 'MyException'. However, when it is deployed to a new environment the parameter received by errorCallBack is a Promise with the status - 'Pending' and the catch in the errorCallBack function is hit.

Fetch:

    fetch(request)
        .then(response => {
            if (!response.ok) {
                errorCallBack(response.json());
                return;
            }
            successCallBack();
        })
        .catch(error => {
            console.log(error.message);
            errorCallBack();
        });

Error callback:

    errorCallBack = (jsonResponse) => {
        jsonResponse
            .then(data => {
                if (data) {
                    if (data.MyException) {
                        this.setErrorMessage("MyException");
                        return;
                    }
                }
            })
            .catch(() => {
                this.setErrorMessage("");
            });
    }

1 Answers1

0

Some changes. response.json() can fail if you are returning an empty response, but you can add your logic there.

 fetch(request)
        .then(response => {
            if (!response.ok) {
                console.log(response.status) // Error code
                console.log(response.statusText); // Error message
                return errorCallBack(response.json()); // return response Promise
            }

            return successCallBack(response.json()); // This will return a Promise
        })
        .catch(error => {     
            console.log(error); // Log any error
            errorCallBack(error); // return an error object
        });

handle Error

errorCallBack = (response) => {

   response
   .then(jsonData => {

      if(jsonData.myException) {
         ...
      } else{
         ...
      }

   })
   .catch(error => {
      console.log(error)
      ...
   })
}
Oscar Rendón
  • 52
  • 1
  • 8