Skip to content

Commit

Permalink
feat: return more helpful error when authentication fails (#480)
Browse files Browse the repository at this point in the history
* feat: return more helpful error when authentication fails
  • Loading branch information
stephenplusplus committed Sep 11, 2019
1 parent 59287a9 commit 98d2b7f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -600,6 +600,7 @@ export class Util {
err: Error | null,
authenticatedReqOpts?: DecorateRequestOptions
) => {
const authLibraryError = err;
const autoAuthFailed =
err &&
err.message.indexOf('Could not load the default credentials') > -1;
Expand Down Expand Up @@ -651,7 +652,17 @@ export class Util {
activeRequest_ = util.makeRequest(
authenticatedReqOpts!,
reqConfig,
callback!
(apiResponseError, ...params) => {
if (
apiResponseError &&
(apiResponseError as ApiError).code === 401
) {
// Re-use the "Could not load the default credentials error" if
// the API request failed due to missing credentials.
apiResponseError = authLibraryError;
}
callback!(apiResponseError, ...params);
}
);
}
};
Expand Down
31 changes: 31 additions & 0 deletions test/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -925,6 +925,37 @@ describe('common/util', () => {
});
});

it('should block 401 API errors', done => {
const authClientError = new Error(
'Could not load the default credentials'
);
authClient.authorizeRequest = async () => {
throw authClientError;
};
sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient);

const makeRequestArg1 = new Error('API 401 Error.') as ApiError;
makeRequestArg1.code = 401;
const makeRequestArg2 = {};
const makeRequestArg3 = {};
stub('makeRequest', (authenticatedReqOpts, cfg, callback) => {
callback(makeRequestArg1, makeRequestArg2, makeRequestArg3);
});

const makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory(
{}
);
makeAuthenticatedRequest(
{} as DecorateRequestOptions,
(arg1, arg2, arg3) => {
assert.strictEqual(arg1, authClientError);
assert.strictEqual(arg2, makeRequestArg2);
assert.strictEqual(arg3, makeRequestArg3);
done();
}
);
});

it('should block decorateRequest error', done => {
const decorateRequestError = new Error('Error.');
sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient);
Expand Down

0 comments on commit 98d2b7f

Please sign in to comment.