Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix undefined error messages when using the lib on the client side #158

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 31 additions & 19 deletions src/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,28 +48,26 @@ export default class Http {
return new Promise((resolve, reject) => {
const request = new window.XMLHttpRequest();
request.open(method, url);
request.onload = function() {
request.onload = function () {
let response;
try {
const response = JSON.parse(request.response);

if (request.status.toString() === HTTP_STATUS.OK) {
resolve(response);
} else {
reject(
new Error({
body: response,
status: request.status,
}),
);
}
response = JSON.parse(request.response);
} catch (e) {
reject(
new Error({
body: request.responseText,
status: request.status,
}),
);
// JSON failed to parse. Create a placeholder response.
response = {
error: {
message: 'Failed to parse response JSON.',
}
};
reject(convertXhrErrorToRequestPromiseError(request, response));
return;
}
if (request.status.toString() !== HTTP_STATUS.OK) {
reject(convertXhrErrorToRequestPromiseError(request, response));
return;
}

resolve(response);
};
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');
Expand Down Expand Up @@ -126,3 +124,17 @@ export default class Http {
});
}
}

/**
* Converts the given XHR error to an error that looks like one that would
* be returned by the request-promise API.
* @param {XMLHttpRequest} request
* @param {any} response
*/
function convertXhrErrorToRequestPromiseError(request, response) {
return {
name: 'StatusCodeError',
error: response,
statusCode: request.status,
};
}