From ca4294b398fbed047b9ab9ec7b3b41ac459fb427 Mon Sep 17 00:00:00 2001 From: shadow-light <42055707+shadow-light@users.noreply.github.com> Date: Thu, 20 May 2021 10:44:09 +1000 Subject: [PATCH] Include error response body in thrown fetch errors --- src/xhr.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/xhr.ts b/src/xhr.ts index d5cc760..b8f76fa 100644 --- a/src/xhr.ts +++ b/src/xhr.ts @@ -85,7 +85,7 @@ export class FetchRequestor extends Requestor { requestInit.headers['Accept'] = 'application/json, text/javascript, */*; q=0.01'; } - return fetch(url.toString(), requestInit).then(response => { + return fetch(url.toString(), requestInit).then(async response => { if (response.status >= 200 && response.status < 300) { const contentType = response.headers.get('content-type'); if (isJsonDataType || (contentType && contentType.indexOf('application/json') !== -1)) { @@ -94,7 +94,13 @@ export class FetchRequestor extends Requestor { return response.text(); } } else { - return Promise.reject(new AppAuthError(response.status.toString(), response.statusText)); + // Extract the response's body if possible as usually contains useful error info + let body = ''; + try { + body = await response.text(); + body = JSON.parse(body); + } catch {} + return Promise.reject(new AppAuthError(`${response.status} ${response.statusText}`, body)); } }); }