1

I have created a authFetch function so I can easily include my JWT tokens to all my fetch requests as follows.

export const authFetch = (url, body) => {
    let headers = {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + Auth.getToken()
    }

    let options
    if (body !== null) {
        options = {
            headers,
            body
        }
    } else {
        options = {
            headers
        }
    }

    return fetch(url, {
        headers,
        method: 'POST',
        body: JSON.stringify(body)
    })
        .then(_checkStatus)
        .then(response => response.json())

}

const _checkStatus = response => {
    // raises an error in case response status is not a success
    if (response.status >= 200 && response.status < 300) {
        // Success status lies between 200 to 300
        console.log(response)
        return response
    } else {
        console.log(response)
        let error = new Error(response.statusText)
        error.response = response
        throw error
    }
}

now I have a problem. When my API throws a 404, or 400 error, the error is not throw back to my Component which calls authFetch in componentWillMount.

ReactJS says fail to compound on unhandled errors

Unhandled Rejection (Error): Forbidden _checkStatus src/services/authFetch.js:44
41 | return response
42 | } else {
43 | console.log(response)

44 | let error = new Error(response.statusText)

45 | error.response = response

46 | throw error
47 | }

the arrow is pointed at row 44

Update: Added Component codes

componentWillMount = () => {
    authFetch($url)
    .then(data => {
        console.log(data)
    }
    .catch(err => console.log(err))
}
Someone Special
  • 12,479
  • 7
  • 45
  • 76

0 Answers0