Skip to content

Commit

Permalink
handle fetch request failure and throw error /w message 'Network error'
Browse files Browse the repository at this point in the history
  • Loading branch information
cheedep committed Apr 6, 2018
1 parent 0733d80 commit 7eb3970
Showing 1 changed file with 32 additions and 10 deletions.
42 changes: 32 additions & 10 deletions packages/amazon-cognito-identity-js/src/Client.js
Expand Up @@ -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');
}
throw err;
})
.then(resp => resp.json().catch(() => ({})))
.then(data => {
Expand All @@ -56,17 +63,32 @@ export default class Client {
return callback(error);
})
.catch(err => {
if (err) {
return callback(err);
let code = 'UnknownError', error = {};

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

0 comments on commit 7eb3970

Please sign in to comment.