2

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?

1 Answer 1

3

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()
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.