lquixada / cross-fetch

Universal WHATWG Fetch API for Node, Browsers and React Native.
MIT License
1.67k stars 104 forks source link

How to get error response when failed? #106

Closed tom10271 closed 3 years ago

tom10271 commented 3 years ago
        await fetch(requestUrl, options)
            .then(response => {
                if (response.ok) {
                    return response;
                } else {
                    response.text().then((body) => {
                        console.log({
                            request: {
                                requestUrl,
                                options: clonedOptions,
                            },
                            response: {
                                status: response.status,
                                statusText: response.statusText,
                                headers: response.headers,
                                body,
                            },
                        });
                    });

                    throw new Error('Request failed');
                }
            })
            .catch(error => {
                throw error;
            })
            .then(response => {
                return response.json();
            })

Here is my code and I cannot print it out for debugging

tom10271 commented 3 years ago

With purely await everything works fine

        const response = await fetch(requestUrl, options);

        if (response.ok) {
            return response.json();
        } else {
            const clonedOptions = Object.assign({}, options);

            if (clonedOptions.headers.Authorization) {
                clonedOptions.headers.Authorization = 'Hidden';
            }

            const errorResponse = await response.text();

            console.dir({
                request: {
                    requestUrl,
                    options: clonedOptions,
                },
                response: {
                    status: response.status,
                    statusText: response.statusText,
                    headers: response.headers,
                    errorResponse,
                },
            }, { depth: null });

            throw new Error('Request failed');
        }