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

Callback with error if error thrown due to network #605

Merged
merged 9 commits into from
Apr 19, 2018
43 changes: 33 additions & 10 deletions packages/amazon-cognito-identity-js/src/Client.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export default class Client {
const headers = {
'Content-Type': 'application/x-amz-json-1.1',
'X-Amz-Target': `AWSCognitoIdentityProviderService.${operation}`,
'X-Amz-User-Agent': this.userAgent
'X-Amz-User-Agent': this.userAgent,
};

const options = {
Expand All @@ -40,6 +40,13 @@ export default class Client {
.then(resp => {
response = resp;
return resp;
}, err => {
// If error happens here, the request failed
// if it is TypeError throw network error
if (err instanceof TypeError) {
throw new Error('Network error');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should probably return:
return throw new Error('Network error');

or run an } else {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Throwing an error automatically returns control to the caller. You dont need return or a branch here.

}
throw err;
})
.then(resp => resp.json().catch(() => ({})))
.then(data => {
Expand All @@ -55,15 +62,31 @@ export default class Client {
};
return callback(error);
})
.catch(() => {
// Taken from aws-sdk-js/lib/protocol/json.js
const code = (response.headers.get('x-amzn-errortype') || 'UnknownError').split(':')[0];
const error = {
code,
name: code,
statusCode: response.status,
message: response.status.toString(),
};
.catch(err => {
// default to return 'UnknownError'
let error = { code: 'UnknownError', message: 'Unkown error' };

// first check if we have a service error
if (response && response.headers && response.headers.get('x-amzn-errortype')) {
try {
const code = (response.headers.get('x-amz-errortype')).split(':')[0];
error = {
code,
name: code,
statusCode: response.status,
message: (response.status) ? response.status.toString() : null,
};
} catch (ex) {
// pass through so it doesn't get swallowed if we can't parse it
}
// otherwise check if error is Network error
} else if (err instanceof Error && err.message === 'Network error') {
error = {
code: err.name,
name: err.name,
message: err.message,
};
}
return callback(error);
});
}
Expand Down