简体   繁体   中英

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?

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()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM