Skip to content

Commit

Permalink
chore: use response body message as error message when possible (#297)
Browse files Browse the repository at this point in the history
  • Loading branch information
nolanmar511 authored Sep 27, 2018
1 parent 15ae5e4 commit 1273b00
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions ts/src/profiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,21 +76,33 @@ export interface RequestProfile {
}

/**
* @return number indicated by backoff if the response indicates a backoff and
* that backoff is greater than 0. Otherwise returns undefined.
* @return the message of the response body, if that field exists. Otherwise,
* returns the response status message.
*/
function getServerResponseBackoff(response: http.IncomingMessage): number|
function getResponseErrorMessage(response: http.IncomingMessage): string|
undefined {
// tslint:disable-next-line: no-any
const body = (response as any).body;
if (body && body.message && typeof body.message === 'string') {
return body.message;
}
return response.statusMessage;
}

/**
* @return number indicated by backoff if the response indicates a backoff and
* that backoff is greater than 0. Otherwise returns undefined.
*/
function getServerResponseBackoff(response: http.IncomingMessage): number|
undefined {
// The response currently does not have field containing the server-specified
// backoff. As a workaround, response body's message is parsed to get the
// backoff.
// TODO (issue #250): Remove this workaround and get the retry delay from
// body.error.details.
if (body && body.message && typeof body.message === 'string') {
return parseBackoffDuration(body.message);
const message = getResponseErrorMessage(response);
if (message) {
return parseBackoffDuration(message);
}
return undefined;
}
Expand Down Expand Up @@ -161,8 +173,8 @@ async function profileBytes(p: perftools.profiles.IProfile): Promise<string> {
* Error constructed from HTTP server response which indicates backoff.
*/
class BackoffResponseError extends Error {
constructor(response: http.IncomingMessage, readonly backoffMillis: number) {
super(response.statusMessage);
constructor(message: string|undefined, readonly backoffMillis: number) {
super(message);
}
}

Expand Down Expand Up @@ -211,9 +223,10 @@ function responseToProfileOrError(
response?: http.IncomingMessage): RequestProfile {
// response.statusCode is guaranteed to exist on client requests.
if (response && isErrorResponseStatusCode(response.statusCode!)) {
const message = getResponseErrorMessage(response);
const delayMillis = getServerResponseBackoff(response);
if (delayMillis) {
throw new BackoffResponseError(response, delayMillis);
throw new BackoffResponseError(message, delayMillis);
}
throw new Error(response.statusMessage);
}
Expand Down

0 comments on commit 1273b00

Please sign in to comment.