From d8d736566e6e6f7360fda7b08b563188bc803bd2 Mon Sep 17 00:00:00 2001 From: Federico Brigante Date: Sun, 14 Jan 2024 16:52:17 +0800 Subject: [PATCH] Throw error if server responds with non-OK HTTP status (#82) --- index.js | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index e0b9fed..5678412 100644 --- a/index.js +++ b/index.js @@ -13,6 +13,14 @@ const getURI = (id, projection) => const requiredFields = ['extensionId', 'clientId', 'refreshToken']; +function throwIfNotOk(request, response) { + if (!request.ok) { + const error = new Error(request.statusText ?? 'Unknown error'); + error.response = response; + throw error; + } +} + class APIClient { constructor(options) { if (typeof fetch !== 'function') { @@ -46,7 +54,11 @@ class APIClient { body: readStream, }); - return request.json(); + const response = await request.json(); + + throwIfNotOk(request, response); + + return response; } async publish(target = 'default', token = this.fetchToken()) { @@ -57,7 +69,11 @@ class APIClient { headers: this._headers(await token), }); - return request.json(); + const response = await request.json(); + + throwIfNotOk(request, response); + + return response; } async get(projection = 'DRAFT', token = this.fetchToken()) { @@ -68,7 +84,11 @@ class APIClient { headers: this._headers(await token), }); - return request.json(); + const response = await request.json(); + + throwIfNotOk(request, response); + + return response; } async fetchToken() { @@ -91,6 +111,8 @@ class APIClient { }, }); + await throwIfNotOk(request); + const response = await request.json(); return response.access_token;