Riku
Riku

Reputation: 157

Fetch function never catches error, always runs then(() => block) with undefined response

Im returning fetch function from separate callApi layer, and calling then + catch for it.

Callapi.js

export const callApi = (url, options = {}, headers = {}) => {
  const defaultOptions = {
    headers: {
      'Content-Type': 'application/json',
      ...headers,
    },
    ...options,
  };

  return fetch(url, defaultOptions)
    .then(res => {
      if (!res.ok) {
        throw Error(res.statusText);
      }
      if(res.status === 401)
      return res;
    })
    .catch(error => {
      console.log(error)
    })
}

export default callApi;

Component.js

 const handleSubmit = (e) => {
    e.preventDefault();
    console.log(loginInfo)
    callApi('http://localhost:8080/login',{
        method: 'POST',
          body: JSON.stringify({
            username: loginInfo.email,
            password: loginInfo.password,
      }),
    })
      .then((res => {
          console.log(res)
          setRedirect(true)
        }
      )
      .catch((err) => setError(err)))
  }

Im having a hard time understanding why catch block doesn't fire, when I throw new error, but then block with undefined response fires always. Thanks for your help

Upvotes: 0

Views: 50

Answers (3)

Parzh from Ukraine
Parzh from Ukraine

Reputation: 9855

The problem is that .catch() in Callapi.js will catch all errors thrown from prior .then() in the same file. Therefore, no errors will happen in Component.js.

Try either re-throwing error, as Ross Mackay suggested, or moving the .catch() block to Component.js, — whatever suites you the best.

Upvotes: 1

Dolly
Dolly

Reputation: 2572

What i can see from your code is that if response is correct, you are returning "res", but in catch you are not returning or throwing anything which lead promise to pass in .then()

 .catch(error => {
      throw new Error(error)
    })

Upvotes: 1

Ross Mackay
Ross Mackay

Reputation: 972

It looks like it's to do with this block:

    .catch(error => {
      console.log(error)
    })

As the error is caught it's considered handled and therefor will pass through to the next .then() in handleSubmit

If logging the error is essential in callApi you could consider re-throwing the error

    .catch(error => {
      console.log(error)
      throw error
    })

Upvotes: 1

Related Questions