Agnes J
Agnes J

Reputation: 21

Logging HTTP errors with Fetch API in node.js

I am trying to find the best way to log bad requests using node-fetch. Here is the code I came up with.

let response = fetch(url)
            .then((response) => { 
                if(!response.ok)
                {
                    //get error json from request and throw exception
                }
                return response.json(); 
            })
            .then((json) =>  {
                return json.data;
            })
            .catch((error) => console.log(error));

The problem here is that response.json() returns a promise so I can't use that to extract the error message and construct an exception. I am pretty new to JS so I feel that the solution to this is very straight-forward and it's just going over my head! Could you guys help me out?

Upvotes: 2

Views: 2242

Answers (1)

mousetail
mousetail

Reputation: 8010

I typically do something like this:

fetch(...).then(
    response=>{
        if (response.ok){
            return response.json()
        }
        else {
            return response.json().then(i=>Promise.reject(i))
        }
    }
)

If you have access to await it becomes even simpler:

let response = await fetch(...);
if (!response.ok){
    throw await response.json()
}
else {
    return await response.json()
}

Upvotes: 3

Related Questions