Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetch api get error messages from server rather than generic messages

I'm using redux thunk to fetch some data in an action

function handleErrors(response) {
    console.log(response)
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
}

export const something = (var) => dispatch => {
    fetch(`${url}/something`, {credentials: 'include'})
    .then(handleErrors)
    .then(res => res.json())
    .then(res =>
        dispatch({
            type: SOMETHING,
            payload: res
        })
    )
    .catch(error => 
        dispatch({
            type: ERROR,
            payload: error
        })
    )

my express server on an error responds with 'some error'

return res.status(500).send({ message: 'some error' });

when it fetches and it's an error (500), its message is the generic "Internal Server Error".

how do I get the 'some error' in fetch?

like image 548
totalnoob Avatar asked Mar 23 '26 09:03

totalnoob


1 Answers

Not sure what’s in your handleError. One approach to extract the error message would be something like this

fetch(url)
  .then(res => {
    // Check if response has errors
    if (res.ok) {
      // No errors
      return res.json();
    } else {
       // Has errors, since res.json() returns a Promise, we
       // chain a then here to get the value and return the err value
       // as Promise rejection so that it will go to the 
       // catch handler
       return res.json().then(err => Promise.reject(err));
       // this could also be
       // return res.json().then(err => throw Error(err));
    }
  })
  .then(json => {
    // dispatch success
  })
  .catch(err => {
    // dispatch error
  });
like image 172
jpdelatorre Avatar answered Mar 25 '26 22:03

jpdelatorre