diff options
Diffstat (limited to 'lib/fetchJson.js')
-rw-r--r-- | lib/fetchJson.js | 23 |
1 files changed, 23 insertions, 0 deletions
diff --git a/lib/fetchJson.js b/lib/fetchJson.js new file mode 100644 index 0000000..5db80b5 --- /dev/null +++ b/lib/fetchJson.js @@ -0,0 +1,23 @@ +export default async function fetcher(...args) { + try { + const response = await fetch(...args) + + // if the server replies, there's always some data in json + // if there's a network error, it will throw at the previous line + const data = await response.json() + + if (response.ok) { + return data + } + + const error = new Error(response.statusText) + error.response = response + error.data = data + throw error + } catch (error) { + if (!error.data) { + error.data = {message: error.message} + } + throw error + } +} |