Skip to content

Commit

Permalink
Merge pull request #15 from ripe-tech/jc/feat-better-result-errors
Browse files Browse the repository at this point in the history
feat: better result errors
  • Loading branch information
3rdvision authored Oct 4, 2023
2 parents 215a34e + ff26b54 commit d94a085
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed

* Remove Travis CI - [products/#97](https://github.com/ripe-tech/products/issues/97)
* Better verification of response errors and error message

### Fixed

Expand Down
37 changes: 36 additions & 1 deletion js/base.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { API as BaseAPI, mix, load, conf } from "yonius";
import { API as BaseAPI, mix, load, conf, verify } from "yonius";

import { InvoiceAPI } from "./invoice";
import { SequenceAPI } from "./sequence";
Expand Down Expand Up @@ -28,4 +28,39 @@ export class API extends mix(BaseAPI).with(InvoiceAPI, SequenceAPI, TaxAPI) {
options.params = options.params !== undefined ? options.params : {};
options.params.api_key = this.apiKey;
}

async _handleResponse(response, errorMessage = "Problem in request") {
const result = await this._getResult(response);
const errors = result.errors ? JSON.stringify(result.errors) : null;
verify(!errors, errors, response.status || 500);
verify(response.ok, errorMessage, response.status || 500);
return result;
}

/**
* Obtains the response object from the provided response making sure that the
* content type is respected when doing so.
*
* @param {Response} response The HTTP response resulting from the request
* made by the API client
* @returns {Object|String|Blob} The parsed result value for the provided
* response object taking into account the content type of it.
*/
async _getResult(response) {
let result = null;
if (
response.headers.get("content-type") &&
response.headers.get("content-type").toLowerCase().startsWith("application/json")
) {
result = await response.json();
} else if (
response.headers.get("content-type") &&
response.headers.get("content-type").toLowerCase().startsWith("text/")
) {
result = await response.text();
} else {
result = await response.blob();
}
return result;
}
}

0 comments on commit d94a085

Please sign in to comment.