handle api error cases better

This commit is contained in:
Kyle Spearrin 2017-11-16 11:12:41 -05:00
parent a166dc65b1
commit cd4c2d6d10
1 changed files with 25 additions and 13 deletions

View File

@ -89,18 +89,25 @@ export default class ApiService {
method: 'POST', method: 'POST',
})); }));
const responseJson = await response.json(); let responseJson: any = null;
const typeHeader = response.headers.get('content-type');
if (typeHeader != null && typeHeader.indexOf('application/json') > -1) {
responseJson = await response.json();
}
if (responseJson != null) {
if (response.status === 200) { if (response.status === 200) {
return new IdentityTokenResponse(responseJson); return new IdentityTokenResponse(responseJson);
} else if (response.status === 400 && responseJson && responseJson.TwoFactorProviders2 && } else if (response.status === 400 && responseJson.TwoFactorProviders2 &&
Object.keys(responseJson.TwoFactorProviders2).length) { Object.keys(responseJson.TwoFactorProviders2).length) {
await this.tokenService.clearTwoFactorToken(request.email); await this.tokenService.clearTwoFactorToken(request.email);
return responseJson.TwoFactorProviders2; return responseJson.TwoFactorProviders2;
} else {
return Promise.reject(new ErrorResponse(responseJson, response.status, true));
} }
} }
return Promise.reject(new ErrorResponse(responseJson, response.status, true));
}
async refreshIdentityToken(): Promise<any> { async refreshIdentityToken(): Promise<any> {
try { try {
await this.doRefreshToken(); await this.doRefreshToken();
@ -375,8 +382,13 @@ export default class ApiService {
return null; return null;
} }
const responseJson = await response.json(); let responseJson: any = null;
return new ErrorResponse(responseJson, response.status); const typeHeader = response.headers.get('content-type');
if (typeHeader != null && typeHeader.indexOf('application/json') > -1) {
responseJson = await response.json();
}
return new ErrorResponse(responseJson, response.status, tokenError);
} }
private async handleTokenState(): Promise<string> { private async handleTokenState(): Promise<string> {
@ -389,7 +401,6 @@ export default class ApiService {
} }
return 'Bearer ' + accessToken; return 'Bearer ' + accessToken;
// TODO: handle error
} }
private async doRefreshToken(): Promise<IdentityTokenResponse> { private async doRefreshToken(): Promise<IdentityTokenResponse> {
@ -418,7 +429,8 @@ export default class ApiService {
await this.tokenService.setTokens(tokenResponse.accessToken, tokenResponse.refreshToken); await this.tokenService.setTokens(tokenResponse.accessToken, tokenResponse.refreshToken);
return tokenResponse; return tokenResponse;
} else { } else {
return Promise.reject(response); const error = await this.handleError(response, true);
return Promise.reject(error);
} }
} }