How to get readable error response from javascript Fetch api?

I am working on Reactjs redux on the front-end and Rails api as the back-end.

So now I am calling the API using the Fetch API method, but the problem is that I cannot get a readable error message similar to the one I received on the network tabs

this is my function

export function create_user(user,userInfoParams={}) {

    return function (dispatch) {
        dispatch(update_user(user));

        return fetch(deafaultUrl + '/v1/users/',
            {
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                method: "POST",
                body: JSON.stringify(userInfoParams)
            })
            .then(function(response) {
                console.log(response);
                console.log(response.body);
                console.log(response.message);
                console.log(response.errors);
                console.log(response.json());
                dispatch(update_errors(response));

                if (response.status >= 400) {
                    throw new Error("Bad response from server");
                }

            })
            .then(function(json){
                console.log("succeed json re");
                // We can dispatch many times!
                // Here, we update the app state with the results of the API call.

                dispatch(update_user(json));

            });


    }
}

But when errors occurred, I can’t understand how to get a readable response message that I receive when I check the network tabs of my browser

So this is what I got from the network tabs when I got errors.

enter image description here

My console

enter image description here

This is the code for my rail

def create
    user = User.new(user_params)
    if user.save
      #UserMailer.account_activation(user).deliver_now
      render json: user, status: 201
    else
      render json: { errors: user.errors }, status: 422
    end
  end

But I can’t understand how I can get this in my function

Thank!

+8
source share
5 answers

, , , , .

, , .

fetch(bla)
    .then(res => {
      if(!res.ok) {
        res.text().then(text => throw Error(text))
       }
      else {
       return res.json();
     }    
    })
    .catch(err => {
       console.log('caught it!',err);
    }
+7

, ... , , response.text() , . , ( ok) . catch.

- -:

const fetchJSON = (...args) => {
  return fetch(...args)
    .then(res => {
      if(res.ok) {
        return res.json()
      }
      return res.text().then(text => {throw new Error(text)})
    })
}

, , , , :

fetchJSON(url, options)
  .then((json) => {
    // do things with the response, like setting state:
    this.setState({ something: json })
  })
  .catch(error => {
    // do things with the error, like logging them:
    console.error(error)
  })
0

, -

export function create_user(user,userInfoParams={}) {

  return function (dispatch) {
    dispatch(update_user(user));

    return fetch(deafaultUrl + '/v1/users/',
        {
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            method: "POST",
            body: JSON.stringify(userInfoParams)
        })
        .then(function(response) {
            console.log(response);
            console.log(response.body);
            console.log(response.message);
            console.log(response.errors);
            console.log(response.json());
            return response.json();
        })
        .then(function(object){
          if (object.errors) {
            dispatch(update_errors(response));
            throw new Error(object.errors);
          } else {
            console.log("succeed json re");
            dispatch(update_user(json));
          }
        })
        .catch(function(error){
          this.setState({ error })
        })
       }
     }
0

response.body response.message.

You need to check the error attribute for the response object.

if(response.errors) {
    console.error(response.errors)
}

Check out https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

In fact, you should return the error response code from the server and use the .catch()fetch API function

-1
source

First you need to call the json method for your answer.

Example:

fetch(`${API_URL}`, {
        method: 'post',
        headers: {
           'Accept': 'application/json',
           'Content-Type': 'application/json'
        },
        body: JSON.stringify(userInfoParams)
    })
    .then((response) => response.json())
    .then((response) => console.log(response)) 
    .catch((err) => {
        console.log("error", err) 
    });

Let me know the console log if it doesn't work for you.

-1
source

Source: https://habr.com/ru/post/1659757/


All Articles