Skip to content

Commit

Permalink
chore: Improve shareability of error functions (#12048)
Browse files Browse the repository at this point in the history
Co-authored-by: Aaron S <[email protected]>
  • Loading branch information
cshfang and stocaaro authored Sep 21, 2023
1 parent a85686a commit f1613e2
Show file tree
Hide file tree
Showing 44 changed files with 359 additions and 267 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import getConfig from 'next/config';
import { parseAWSExports } from '@aws-amplify/core/internals/utils';
import { getAmplifyConfig } from '../../src/utils/getAmplifyConfig';
import { AmplifyError } from '@aws-amplify/core/internals/utils';

jest.mock('next/config');
jest.mock('@aws-amplify/core/internals/utils');
Expand Down Expand Up @@ -80,6 +79,6 @@ describe('getAmplifyConfig', () => {
});

it('should throw error when amplifyConfig is not found from env vars', () => {
expect(() => getAmplifyConfig()).toThrow(AmplifyError);
expect(() => getAmplifyConfig()).toThrow();
});
});
7 changes: 5 additions & 2 deletions packages/analytics/src/errors/AnalyticsError.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { AmplifyError, ErrorParams } from '@aws-amplify/core/internals/utils';
import {
AmplifyError,
AmplifyErrorParams,
} from '@aws-amplify/core/internals/utils';

/**
* @internal
*/
export class AnalyticsError extends AmplifyError {
constructor(params: ErrorParams) {
constructor(params: AmplifyErrorParams) {
super(params);

// Hack for making the custom error class work when transpiled to es5
Expand Down
7 changes: 5 additions & 2 deletions packages/api-graphql/src/utils/errors/APIError.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { AmplifyError, ErrorParams } from '@aws-amplify/core/internals/utils';
import {
AmplifyError,
AmplifyErrorParams,
} from '@aws-amplify/core/internals/utils';

/**
* @internal
*/
export class APIError extends AmplifyError {
constructor(params: ErrorParams) {
constructor(params: AmplifyErrorParams) {
super(params);

// Hack for making the custom error class work when transpiled to es5
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AmplifyErrorString } from '@aws-amplify/core/internals/utils';
import { AmplifyErrorCode } from '@aws-amplify/core/internals/utils';
import { assertServiceError } from '../../../src/errors/utils/assertServiceError';
import { AuthError } from '../../../src/errors/AuthError';
import { InitiateAuthException } from '../../../src/providers/cognito/types/errors';
Expand All @@ -10,7 +10,7 @@ describe('asserts service errors', () => {
expect(assertServiceError(error)).toThrowError();
} catch (error) {
expect(error).toBeInstanceOf(AuthError);
expect(error.name).toBe(AmplifyErrorString.UNKNOWN);
expect(error.name).toBe(AmplifyErrorCode.Unknown);
}
});
test('it should throw an unknown error when error is a TypeError', () => {
Expand All @@ -19,7 +19,7 @@ describe('asserts service errors', () => {
expect(assertServiceError(error)).toThrowError();
} catch (error) {
expect(error).toBeInstanceOf(AuthError);
expect(error.name).toBe(AmplifyErrorString.UNKNOWN);
expect(error.name).toBe(AmplifyErrorCode.Unknown);
}
});
test('it should throw an unknown error when error does not have a name', () => {
Expand All @@ -28,7 +28,7 @@ describe('asserts service errors', () => {
expect(assertServiceError(error)).toThrowError();
} catch (error) {
expect(error).toBeInstanceOf(AuthError);
expect(error.name).toBe(AmplifyErrorString.UNKNOWN);
expect(error.name).toBe(AmplifyErrorCode.Unknown);
}
});
test('it should not throw if the error is coming from the service', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,7 @@ const authConfig = {
userPoolId: 'us-west-2_zzzzz',
},
};
const authConfigWithClientmetadata = {
Cognito: {
userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398',
userPoolId: 'us-west-2_zzzzz',
},
};

CognitoUserPoolsTokenProvider.setAuthConfig(authConfig);
Amplify.configure({
Auth: authConfig,
Expand Down
7 changes: 5 additions & 2 deletions packages/auth/src/errors/AuthError.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { AmplifyError, ErrorParams } from '@aws-amplify/core/internals/utils';
import {
AmplifyError,
AmplifyErrorParams,
} from '@aws-amplify/core/internals/utils';

export class AuthError extends AmplifyError {
constructor(params: ErrorParams) {
constructor(params: AmplifyErrorParams) {
super(params);

// Hack for making the custom error class work when transpiled to es5
Expand Down
7 changes: 5 additions & 2 deletions packages/auth/src/errors/utils/assertServiceError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
// SPDX-License-Identifier: Apache-2.0

import { AuthError } from '../AuthError';
import { AmplifyErrorString, ServiceError } from '@aws-amplify/core/internals/utils';
import {
AmplifyErrorCode,
ServiceError,
} from '@aws-amplify/core/internals/utils';

export function assertServiceError(
error: unknown
Expand All @@ -13,7 +16,7 @@ export function assertServiceError(
error instanceof TypeError
) {
throw new AuthError({
name: AmplifyErrorString.UNKNOWN,
name: AmplifyErrorCode.Unknown,
message: 'An unknown error has ocurred.',
underlyingError: error,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
Identity,
KeyValueStorageInterface,
} from '@aws-amplify/core';
import { assertIdentityPooIdConfig } from '@aws-amplify/core/internals/utils';
import { assertIdentityPoolIdConfig } from '@aws-amplify/core/internals/utils';
import { IdentityIdStorageKeys, IdentityIdStore } from './types';
import { getAuthStorageKeys } from '../tokenProvider/TokenStore';
import { AuthKeys } from '../tokenProvider/types';
Expand All @@ -19,7 +19,7 @@ export class DefaultIdentityIdStore implements IdentityIdStore {
_primaryIdentityId: string | undefined;
_authKeys: AuthKeys<string> = {};
setAuthConfig(authConfigParam: AuthConfig) {
assertIdentityPooIdConfig(authConfigParam.Cognito);
assertIdentityPoolIdConfig(authConfigParam.Cognito);
this.authConfig = authConfigParam;
this._authKeys = createKeysForAuthStorage(
'Cognito',
Expand All @@ -33,7 +33,7 @@ export class DefaultIdentityIdStore implements IdentityIdStore {
}

async loadIdentityId(): Promise<Identity | null> {
assertIdentityPooIdConfig(this.authConfig?.Cognito);
assertIdentityPoolIdConfig(this.authConfig?.Cognito);
// TODO(v6): migration logic should be here
try {
if (!!this._primaryIdentityId) {
Expand All @@ -60,7 +60,7 @@ export class DefaultIdentityIdStore implements IdentityIdStore {
}

async storeIdentityId(identity: Identity): Promise<void> {
assertIdentityPooIdConfig(this.authConfig?.Cognito);
assertIdentityPoolIdConfig(this.authConfig?.Cognito);

if (identity.type === 'guest') {
this.keyValueStorage.setItem(this._authKeys.identityId, identity.id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
} from '@aws-amplify/core';
import {
Logger,
assertIdentityPooIdConfig,
assertIdentityPoolIdConfig,
decodeJWT,
CognitoIdentityPoolConfig,
} from '@aws-amplify/core/internals/utils';
Expand Down Expand Up @@ -55,7 +55,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider
const tokens = getCredentialsOptions.tokens;
const authConfig = getCredentialsOptions.authConfig;
try {
assertIdentityPooIdConfig(authConfig?.Cognito);
assertIdentityPoolIdConfig(authConfig?.Cognito);
} catch {
// No identity pool configured, skipping
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import { AuthConfig, KeyValueStorageInterface } from '@aws-amplify/core';
import {
assertTokenProviderConfig,
asserts,
decodeJWT,
} from '@aws-amplify/core/internals/utils';
import {
Expand All @@ -13,6 +12,7 @@ import {
CognitoAuthTokens,
} from './types';
import { AuthError } from '../../../errors/AuthError';
import { assert, TokenProviderErrorCode } from './errorHelpers';

export class DefaultTokenStore implements AuthTokenStore {
private authConfig?: AuthConfig;
Expand Down Expand Up @@ -85,11 +85,7 @@ export class DefaultTokenStore implements AuthTokenStore {
}
}
async storeTokens(tokens: CognitoAuthTokens): Promise<void> {
asserts(!(tokens === undefined), {
message: 'Invalid tokens',
name: 'InvalidAuthTokens',
recoverySuggestion: 'Make sure the tokens are valid',
});
assert(!(tokens === undefined), TokenProviderErrorCode.InvalidAuthTokens);
assertTokenProviderConfig(this.authConfig?.Cognito);

const name = 'Cognito'; // TODO(v6): update after API review for Amplify.configure
Expand Down
22 changes: 22 additions & 0 deletions packages/auth/src/providers/cognito/tokenProvider/errorHelpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import {
AmplifyErrorMap,
AssertionFunction,
createAssertionFunction,
} from '@aws-amplify/core/internals/utils';

export enum TokenProviderErrorCode {
InvalidAuthTokens = 'InvalidAuthTokens',
}

const tokenValidationErrorMap: AmplifyErrorMap<TokenProviderErrorCode> = {
[TokenProviderErrorCode.InvalidAuthTokens]: {
message: 'Invalid tokens.',
recoverySuggestion: 'Make sure the tokens are valid.',
},
};

export const assert: AssertionFunction<TokenProviderErrorCode> =
createAssertionFunction(tokenValidationErrorMap);
17 changes: 0 additions & 17 deletions packages/core/__tests__/Errors.test.ts

This file was deleted.

3 changes: 2 additions & 1 deletion packages/core/__tests__/ServiceWorker.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { AmplifyError, ServiceWorker } from '../src/libraryUtils';
import { ServiceWorkerErrorCode } from '../src/ServiceWorker/errorHelpers';

describe('ServiceWorker test', () => {
describe('Error conditions', () => {
Expand Down Expand Up @@ -28,7 +29,7 @@ describe('ServiceWorker test', () => {
await serviceWorker.register();
} catch (e) {
expect(e).toBeInstanceOf(AmplifyError);
expect(e.name).toBe('ServiceWorkerException');
expect(e.name).toBe(ServiceWorkerErrorCode.Unavailable);
}
});
});
Expand Down
22 changes: 11 additions & 11 deletions packages/core/__tests__/providers/pinpoint/apis/record.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ describe('Pinpoint Provider API: record', () => {
mockBufferPush.mockReset();
mockGetEventBuffer.mockReturnValue({
push: mockBufferPush,
})
});
});

it('uses an existing enpoint if available', async () => {
Expand All @@ -52,16 +52,16 @@ describe('Pinpoint Provider API: record', () => {
identityId,
region,
});

expect(mockUpdateEndpoint).not.toBeCalled();
expect(mockBufferPush).toBeCalledWith(
expect.objectContaining({
endpointId,
event,
session: expect.any(Object),
timestamp: expect.any(String)
}
));
timestamp: expect.any(String),
})
);
});

it("prepares an endpoint if one hasn't been setup", async () => {
Expand All @@ -75,7 +75,7 @@ describe('Pinpoint Provider API: record', () => {
identityId,
region,
});

expect(mockUpdateEndpoint).toBeCalledWith({
appId,
category,
Expand All @@ -94,7 +94,7 @@ describe('Pinpoint Provider API: record', () => {
identityId,
region,
});

expect(mockClientPutEvents).not.toBeCalled();
});

Expand All @@ -121,15 +121,15 @@ describe('Pinpoint Provider API: record', () => {
identityId,
region,
});

expect(mockBufferPush).toBeCalledWith(
expect.objectContaining({
endpointId,
event,
session: expect.any(Object),
timestamp: expect.any(String)
}
));
timestamp: expect.any(String),
})
);
});

it('throws an error if it is unable to determine the endpoint ID', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* @jest-environment node
*/

import { AmplifyError, AmplifyErrorString } from '../../src/Util/Errors';
import { AmplifyError, AmplifyErrorCode } from '../../src/libraryUtils';
import { defaultStorage, sessionStorage } from '../../src/storage';

const key = 'k';
Expand All @@ -14,7 +14,7 @@ describe('test mechanisms', () => {
await defaultStorage.setItem(key, value);
} catch (error) {
expect(error).toBeInstanceOf(AmplifyError);
expect(error.name).toBe(AmplifyErrorString.PLATFORM_NOT_SUPPORTED_ERROR);
expect(error.name).toBe(AmplifyErrorCode.PlatformNotSupported);
}
});

Expand All @@ -23,7 +23,7 @@ describe('test mechanisms', () => {
await sessionStorage.setItem(key, value);
} catch (error) {
expect(error).toBeInstanceOf(AmplifyError);
expect(error.name).toBe(AmplifyErrorString.PLATFORM_NOT_SUPPORTED_ERROR);
expect(error.name).toBe(AmplifyErrorCode.PlatformNotSupported);
}
});
});
19 changes: 19 additions & 0 deletions packages/core/src/AwsClients/Pinpoint/errorHelpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { createAssertionFunction } from '../../errors';
import { AmplifyErrorMap, AssertionFunction } from '../../types';

export enum PinpointValidationErrorCode {
NoAppId = 'NoAppId',
}

const pinpointValidationErrorMap: AmplifyErrorMap<PinpointValidationErrorCode> =
{
[PinpointValidationErrorCode.NoAppId]: {
message: 'Missing application id.',
},
};

export const assert: AssertionFunction<PinpointValidationErrorCode> =
createAssertionFunction(pinpointValidationErrorMap);
Loading

0 comments on commit f1613e2

Please sign in to comment.