From 62c6522b1b0d5f6626e3429fdb31cb0c07cd8075 Mon Sep 17 00:00:00 2001 From: "Grot (@grafanabot)" <43478413+grafanabot@users.noreply.github.com> Date: Fri, 18 Feb 2022 15:24:16 +0000 Subject: [PATCH] Fix: JSON parsing in backend_srv (#45598) (#45615) * fix(plugins/state): console log errors during install / uninstall * fix(backend_srv): catch JSON parse errors Sometimes it can happen that a backend API responses says that it's returning with a JSON content-type, however it actually returns an invalid JSON (e.g. an empty body) - in which case the backendSrv() request errors out. (cherry picked from commit 1e21184f65c76aa37ef6288b71f9d37ada6029fc) Co-authored-by: Levente Balogh --- public/app/core/utils/fetch.ts | 7 ++++++- public/app/features/plugins/admin/state/actions.ts | 4 ++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/public/app/core/utils/fetch.ts b/public/app/core/utils/fetch.ts index 284a5848309..fb77a6d1a7d 100644 --- a/public/app/core/utils/fetch.ts +++ b/public/app/core/utils/fetch.ts @@ -105,7 +105,12 @@ export async function parseResponseBody( return response.blob() as any; case 'json': - return response.json(); + try { + return await response.json(); + } catch (err) { + console.warn(`${response.url} returned an invalid JSON -`, err); + return {} as unknown as T; + } case 'text': return response.text() as any; diff --git a/public/app/features/plugins/admin/state/actions.ts b/public/app/features/plugins/admin/state/actions.ts index 68a47c7ebad..e23bf4b0b0e 100644 --- a/public/app/features/plugins/admin/state/actions.ts +++ b/public/app/features/plugins/admin/state/actions.ts @@ -73,6 +73,8 @@ export const install = createAsyncThunk( return { id, changes } as Update; } catch (e) { + console.error(e); + return thunkApi.rejectWithValue('Unknown error.'); } } @@ -90,6 +92,8 @@ export const uninstall = createAsyncThunk(`${STATE_PREFIX}/uninstall`, async (id changes: { isInstalled: false, installedVersion: undefined }, } as Update; } catch (e) { + console.error(e); + return thunkApi.rejectWithValue('Unknown error.'); } });