3

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?

1
  • try this github.com/github/fetch/issues/203#issuecomment-143347675 Feb 4, 2020 at 9:52

1 Answer 1

7

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
  });
5
  • You can replace your handleError function with the first then on this answer and remove your .then(res) => res.json() Apr 12, 2018 at 16:46
  • can you explain to me how your code gets the actual response and not the generic one please?
    – totalnoob
    Apr 13, 2018 at 7:05
  • Updated my answer to include some explanations. Hope that helps Apr 14, 2018 at 10:43
  • @totalnoob let me know if there’s anything unclear, otherwise please accept the answer Apr 15, 2018 at 13:56
  • @jpdelatorre When I apply above, I get the error of "Uncaught (in promise) SyntaxError: Unexpected end of JSON input". How do I fix this Apr 11, 2021 at 17:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.