Skip to content

Commit

Permalink
Throw error if server responds with non-OK HTTP status (#82)
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante committed Jan 14, 2024
1 parent 57f210c commit d8d7365
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions index.js
Expand Up @@ -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') {
Expand Down Expand Up @@ -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()) {
Expand All @@ -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()) {
Expand All @@ -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() {
Expand All @@ -91,6 +111,8 @@ class APIClient {
},
});

await throwIfNotOk(request);

const response = await request.json();

return response.access_token;
Expand Down

0 comments on commit d8d7365

Please sign in to comment.