Handle empty API responses

This commit is contained in:
D. Berge
2020-08-16 10:51:55 +02:00
parent c93188a5a7
commit d33947e11a

View File

@@ -4,7 +4,18 @@ async function api ({state, commit, dispatch}, [resource, init = {}]) {
// this.loading = true; // this.loading = true;
const res = await fetch(`${state.apiUrl}${resource}`, init); const res = await fetch(`${state.apiUrl}${resource}`, init);
if (res.ok) { if (res.ok) {
return await res.json(); try {
return await res.json();
} catch (err) {
if (err instanceof SyntaxError) {
if (Number(res.headers.get("Content-Length")) === 0) {
// res.json() cannot parse an empty response and we
// have run into this case. We just return undefined.
return;
}
}
throw err;
}
} else { } else {
await dispatch('showSnack', [res.statusText, "warning"]); await dispatch('showSnack', [res.statusText, "warning"]);
} }