Re: [whatwg/fetch] Why doesn't `fetch` reject if 400 ≤ status < 600? (#18)

A good workaround is to do a wrapper around fetch like an HttpClient class:
```js
export default class HttpClient {

    static async post(url: string, body: any): Promise<any> {
        return new Promise(async (resolve, reject) => {
            try {
                let result = await fetch(`${process.env.REACT_APP_API_BASE_URL}/${url}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(body)
                });
                if (result.status >= 400) {
                    reject(await result.json());
                } else {
                    resolve(await result.json());
                }
            } catch (err) {
                reject(err);
            }
        });
    }
}
```

Then it can be used like this...
```js
HttpClient.post('/auth/login', {
            email,
            password
        }).then(res => {
            // Success
        }).catch(err => {
           // Error
        });
```

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/fetch/issues/18#issuecomment-726355210

Received on Thursday, 12 November 2020 21:35:38 UTC