diff --git a/packages/adapter-nextjs/__tests__/utils/getAmplifyConfig.test.ts b/packages/adapter-nextjs/__tests__/utils/getAmplifyConfig.test.ts index cebfc2ac376..8c22885b713 100644 --- a/packages/adapter-nextjs/__tests__/utils/getAmplifyConfig.test.ts +++ b/packages/adapter-nextjs/__tests__/utils/getAmplifyConfig.test.ts @@ -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'); @@ -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(); }); }); diff --git a/packages/analytics/src/errors/AnalyticsError.ts b/packages/analytics/src/errors/AnalyticsError.ts index 0a15987f9d9..a3c1c29ac6a 100644 --- a/packages/analytics/src/errors/AnalyticsError.ts +++ b/packages/analytics/src/errors/AnalyticsError.ts @@ -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 diff --git a/packages/api-graphql/src/utils/errors/APIError.ts b/packages/api-graphql/src/utils/errors/APIError.ts index 01945a2bc65..1c2908f05e8 100644 --- a/packages/api-graphql/src/utils/errors/APIError.ts +++ b/packages/api-graphql/src/utils/errors/APIError.ts @@ -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 diff --git a/packages/auth/__tests__/providers/cognito/assertServiceError.test.ts b/packages/auth/__tests__/providers/cognito/assertServiceError.test.ts index 21b90a6c96e..2d9a4e0a3e1 100644 --- a/packages/auth/__tests__/providers/cognito/assertServiceError.test.ts +++ b/packages/auth/__tests__/providers/cognito/assertServiceError.test.ts @@ -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'; @@ -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', () => { @@ -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', () => { @@ -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', () => { diff --git a/packages/auth/__tests__/providers/cognito/signInWithSRP.test.ts b/packages/auth/__tests__/providers/cognito/signInWithSRP.test.ts index 55f2968d754..e745e1388f2 100644 --- a/packages/auth/__tests__/providers/cognito/signInWithSRP.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInWithSRP.test.ts @@ -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, diff --git a/packages/auth/src/errors/AuthError.ts b/packages/auth/src/errors/AuthError.ts index 408130645c3..ef3e6006e25 100644 --- a/packages/auth/src/errors/AuthError.ts +++ b/packages/auth/src/errors/AuthError.ts @@ -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 diff --git a/packages/auth/src/errors/utils/assertServiceError.ts b/packages/auth/src/errors/utils/assertServiceError.ts index 615d4c023cd..2185383cc80 100644 --- a/packages/auth/src/errors/utils/assertServiceError.ts +++ b/packages/auth/src/errors/utils/assertServiceError.ts @@ -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 @@ -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, }); diff --git a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts index c2013c03621..2a7e6c6124e 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts @@ -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'; @@ -19,7 +19,7 @@ export class DefaultIdentityIdStore implements IdentityIdStore { _primaryIdentityId: string | undefined; _authKeys: AuthKeys = {}; setAuthConfig(authConfigParam: AuthConfig) { - assertIdentityPooIdConfig(authConfigParam.Cognito); + assertIdentityPoolIdConfig(authConfigParam.Cognito); this.authConfig = authConfigParam; this._authKeys = createKeysForAuthStorage( 'Cognito', @@ -33,7 +33,7 @@ export class DefaultIdentityIdStore implements IdentityIdStore { } async loadIdentityId(): Promise { - assertIdentityPooIdConfig(this.authConfig?.Cognito); + assertIdentityPoolIdConfig(this.authConfig?.Cognito); // TODO(v6): migration logic should be here try { if (!!this._primaryIdentityId) { @@ -60,7 +60,7 @@ export class DefaultIdentityIdStore implements IdentityIdStore { } async storeIdentityId(identity: Identity): Promise { - assertIdentityPooIdConfig(this.authConfig?.Cognito); + assertIdentityPoolIdConfig(this.authConfig?.Cognito); if (identity.type === 'guest') { this.keyValueStorage.setItem(this._authKeys.identityId, identity.id); diff --git a/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts b/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts index 0c3cfb5cd8a..0d9b92208a9 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts @@ -11,7 +11,7 @@ import { } from '@aws-amplify/core'; import { Logger, - assertIdentityPooIdConfig, + assertIdentityPoolIdConfig, decodeJWT, CognitoIdentityPoolConfig, } from '@aws-amplify/core/internals/utils'; @@ -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; diff --git a/packages/auth/src/providers/cognito/tokenProvider/TokenStore.ts b/packages/auth/src/providers/cognito/tokenProvider/TokenStore.ts index dd7c5a6468d..6cf45cd9bdb 100644 --- a/packages/auth/src/providers/cognito/tokenProvider/TokenStore.ts +++ b/packages/auth/src/providers/cognito/tokenProvider/TokenStore.ts @@ -3,7 +3,6 @@ import { AuthConfig, KeyValueStorageInterface } from '@aws-amplify/core'; import { assertTokenProviderConfig, - asserts, decodeJWT, } from '@aws-amplify/core/internals/utils'; import { @@ -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; @@ -85,11 +85,7 @@ export class DefaultTokenStore implements AuthTokenStore { } } async storeTokens(tokens: CognitoAuthTokens): Promise { - 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 diff --git a/packages/auth/src/providers/cognito/tokenProvider/errorHelpers.ts b/packages/auth/src/providers/cognito/tokenProvider/errorHelpers.ts new file mode 100644 index 00000000000..60858f9f3c0 --- /dev/null +++ b/packages/auth/src/providers/cognito/tokenProvider/errorHelpers.ts @@ -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.InvalidAuthTokens]: { + message: 'Invalid tokens.', + recoverySuggestion: 'Make sure the tokens are valid.', + }, +}; + +export const assert: AssertionFunction = + createAssertionFunction(tokenValidationErrorMap); diff --git a/packages/core/__tests__/Errors.test.ts b/packages/core/__tests__/Errors.test.ts deleted file mode 100644 index 29c8e574b39..00000000000 --- a/packages/core/__tests__/Errors.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { missingConfig, invalidParameter } from '../src/Util/Errors'; - -describe('Error', () => { - test('Missing Config', () => { - const missingConfigError = missingConfig('someField'); - expect(missingConfigError.message).toEqual( - 'Missing config value of someField' - ); - }); - - test('Invalid Param', () => { - const invalidParameterError = invalidParameter('someArg'); - expect(invalidParameterError.message).toEqual( - 'Invalid parameter value of someArg' - ); - }); -}); diff --git a/packages/core/__tests__/ServiceWorker.test.ts b/packages/core/__tests__/ServiceWorker.test.ts index aa003b97213..ac2bac95836 100644 --- a/packages/core/__tests__/ServiceWorker.test.ts +++ b/packages/core/__tests__/ServiceWorker.test.ts @@ -1,4 +1,5 @@ import { AmplifyError, ServiceWorker } from '../src/libraryUtils'; +import { ServiceWorkerErrorCode } from '../src/ServiceWorker/errorHelpers'; describe('ServiceWorker test', () => { describe('Error conditions', () => { @@ -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); } }); }); diff --git a/packages/core/__tests__/providers/pinpoint/apis/record.test.ts b/packages/core/__tests__/providers/pinpoint/apis/record.test.ts index 11c8ae09b91..85faf1ee2d1 100644 --- a/packages/core/__tests__/providers/pinpoint/apis/record.test.ts +++ b/packages/core/__tests__/providers/pinpoint/apis/record.test.ts @@ -40,7 +40,7 @@ describe('Pinpoint Provider API: record', () => { mockBufferPush.mockReset(); mockGetEventBuffer.mockReturnValue({ push: mockBufferPush, - }) + }); }); it('uses an existing enpoint if available', async () => { @@ -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 () => { @@ -75,7 +75,7 @@ describe('Pinpoint Provider API: record', () => { identityId, region, }); - + expect(mockUpdateEndpoint).toBeCalledWith({ appId, category, @@ -94,7 +94,7 @@ describe('Pinpoint Provider API: record', () => { identityId, region, }); - + expect(mockClientPutEvents).not.toBeCalled(); }); @@ -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 () => { diff --git a/packages/core/__tests__/storage/storage-mechanisms-node-runtime.test.ts b/packages/core/__tests__/storage/storage-mechanisms-node-runtime.test.ts index 28a0e10e728..c895d5fe6b4 100644 --- a/packages/core/__tests__/storage/storage-mechanisms-node-runtime.test.ts +++ b/packages/core/__tests__/storage/storage-mechanisms-node-runtime.test.ts @@ -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'; @@ -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); } }); @@ -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); } }); }); diff --git a/packages/core/src/AwsClients/Pinpoint/errorHelpers.ts b/packages/core/src/AwsClients/Pinpoint/errorHelpers.ts new file mode 100644 index 00000000000..eff5f3784d5 --- /dev/null +++ b/packages/core/src/AwsClients/Pinpoint/errorHelpers.ts @@ -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.NoAppId]: { + message: 'Missing application id.', + }, + }; + +export const assert: AssertionFunction = + createAssertionFunction(pinpointValidationErrorMap); diff --git a/packages/core/src/AwsClients/Pinpoint/putEvents.ts b/packages/core/src/AwsClients/Pinpoint/putEvents.ts index 1982afcdacc..ac73dac7ff4 100644 --- a/packages/core/src/AwsClients/Pinpoint/putEvents.ts +++ b/packages/core/src/AwsClients/Pinpoint/putEvents.ts @@ -1,7 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { asserts } from '../../Util/errors/AssertError'; import { authenticatedHandler } from '../../clients/handlers/authenticated'; import { composeServiceApi } from '../../clients/internal/composeServiceApi'; import { extendedEncodeURIComponent } from '../../clients/middleware/signing/utils/extendedEncodeURIComponent'; @@ -11,8 +10,8 @@ import { parseMetadata, } from '../../clients/serde'; import { Endpoint, HttpRequest, HttpResponse } from '../../clients/types'; -import { APPLICATION_ID_EXCEPTION } from '../../Util/Constants'; import { defaultConfig, getSharedHeaders } from './base'; +import { assert, PinpointValidationErrorCode } from './errorHelpers'; import type { PutEventsCommandInput as PutEventsInput, PutEventsCommandOutput as PutEventsOutput, @@ -24,10 +23,7 @@ const putEventsSerializer = ( { ApplicationId, EventsRequest }: PutEventsInput, endpoint: Endpoint ): HttpRequest => { - asserts(!!ApplicationId, { - name: APPLICATION_ID_EXCEPTION, - message: 'ApplicationId is required for putEvents', - }); + assert(!!ApplicationId, PinpointValidationErrorCode.NoAppId); const headers = getSharedHeaders(); const url = new URL(endpoint.url); url.pathname = `v1/apps/${extendedEncodeURIComponent(ApplicationId)}/events`; diff --git a/packages/core/src/Cache/AsyncStorageCache.ts b/packages/core/src/Cache/AsyncStorageCache.ts index 10ab1e02c1f..ed7f94e1bc5 100644 --- a/packages/core/src/Cache/AsyncStorageCache.ts +++ b/packages/core/src/Cache/AsyncStorageCache.ts @@ -6,11 +6,11 @@ import { ConsoleLogger as Logger } from '../Logger'; import { StorageCache } from './StorageCache'; import { defaultConfig, getCurrTime } from './Utils'; import { CacheConfig, CacheItem, CacheItemOptions, ICache } from './types'; -import { STORAGE_CACHE_EXCEPTION } from '../Util/Constants'; -import { asserts } from '../Util/errors/AssertError'; import { getCurrSizeKey } from './Utils/CacheUtils'; +import { assert, CacheErrorCode } from './Utils/errorHelpers'; const logger = new Logger('AsyncStorageCache'); + /* * Customized cache which based on the AsyncStorage with LRU implemented */ @@ -79,10 +79,7 @@ export class AsyncStorageCache extends StorageCache implements ICache { */ async _isExpired(key: string) { const text = await AsyncStorage.getItem(key); - asserts(text !== null, { - name: STORAGE_CACHE_EXCEPTION, - message: `Item not found in the storage by the key: ${key}.`, - }); + assert(text !== null, CacheErrorCode.NoCacheItem, `Key: ${key}`); const item = JSON.parse(text); if (getCurrTime() >= item.expires) { return true; @@ -98,10 +95,7 @@ export class AsyncStorageCache extends StorageCache implements ICache { */ async _removeItem(prefixedKey: string, size?: number) { const config = await AsyncStorage.getItem(prefixedKey); - asserts(!!config, { - name: STORAGE_CACHE_EXCEPTION, - message: `Item not found in the storage by the key: ${prefixedKey}.`, - }); + assert(!!config, CacheErrorCode.NoCacheItem, `Key: ${prefixedKey}`); const itemSize = size ?? JSON.parse(config).byteSize; // first try to update the current size of the cache await this._decreaseCurSizeInBytes(itemSize); diff --git a/packages/core/src/Cache/BrowserStorageCache.ts b/packages/core/src/Cache/BrowserStorageCache.ts index b79746232e7..373bf44856f 100644 --- a/packages/core/src/Cache/BrowserStorageCache.ts +++ b/packages/core/src/Cache/BrowserStorageCache.ts @@ -5,9 +5,8 @@ import { ConsoleLogger as Logger } from '../Logger'; import { defaultConfig, getCurrTime } from './Utils'; import { StorageCache } from './StorageCache'; import { ICache, CacheConfig, CacheItem, CacheItemOptions } from './types'; -import { asserts } from '../Util/errors/AssertError'; -import { STORAGE_CACHE_EXCEPTION } from '../Util/Constants'; import { getCurrSizeKey } from './Utils/CacheUtils'; +import { assert, CacheErrorCode } from './Utils/errorHelpers'; const logger = new Logger('Cache'); @@ -22,20 +21,14 @@ export class BrowserStorageCacheClass extends StorageCache implements ICache { constructor(config?: CacheConfig) { super(config); - asserts(!!this.cacheConfig.storage, { - name: STORAGE_CACHE_EXCEPTION, - message: 'Storage is not defined in the cache config', - }); + assert(!!this.cacheConfig.storage, CacheErrorCode.NoCacheStorage); this.cacheConfig.storage = this.cacheConfig.storage; this.getItem = this.getItem.bind(this); this.setItem = this.setItem.bind(this); this.removeItem = this.removeItem.bind(this); } private getStorage(): Storage { - asserts(!!this.cacheConfig.storage, { - name: STORAGE_CACHE_EXCEPTION, - message: 'Storage is not defined in the cache config', - }); + assert(!!this.cacheConfig.storage, CacheErrorCode.NoCacheStorage); return this.cacheConfig.storage; } /** @@ -91,10 +84,7 @@ export class BrowserStorageCacheClass extends StorageCache implements ICache { */ private _isExpired(key: string): boolean { const text: string | null = this.getStorage().getItem(key); - asserts(text !== null, { - name: STORAGE_CACHE_EXCEPTION, - message: `Item not found in the storage by the key: ${key}.`, - }); + assert(text !== null, CacheErrorCode.NoCacheItem, `Key: ${key}`); const item: CacheItem = JSON.parse(text); if (getCurrTime() >= item.expires) { return true; @@ -111,10 +101,7 @@ export class BrowserStorageCacheClass extends StorageCache implements ICache { */ private _removeItem(prefixedKey: string, size?: number): void { const item = this.getStorage().getItem(prefixedKey); - asserts(item !== null, { - name: STORAGE_CACHE_EXCEPTION, - message: `Item not found in the storage by the key: ${prefixedKey}.`, - }); + assert(item !== null, CacheErrorCode.NoCacheItem, `Key: ${prefixedKey}`); const itemSize: number = size ?? JSON.parse(item).byteSize; this._decreaseCurSizeInBytes(itemSize); // remove the cache item diff --git a/packages/core/src/Cache/InMemoryCache.ts b/packages/core/src/Cache/InMemoryCache.ts index 0bf7259fde4..59ed6e9cd69 100644 --- a/packages/core/src/Cache/InMemoryCache.ts +++ b/packages/core/src/Cache/InMemoryCache.ts @@ -1,14 +1,13 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { CacheList, defaultConfig, getCurrTime, CacheObject } from './Utils'; +import { CacheList, getCurrTime, CacheObject } from './Utils'; import { StorageCache } from './StorageCache'; import { ICache, CacheConfig, CacheItem, CacheItemOptions } from './types'; import { ConsoleLogger as Logger } from '../Logger'; -import { asserts } from '../Util/errors/AssertError'; -import { STORAGE_CACHE_EXCEPTION } from '../Util/Constants'; import { getCurrSizeKey } from './Utils/CacheUtils'; +import { assert, CacheErrorCode } from './Utils/errorHelpers'; const logger = new Logger('InMemoryCache'); @@ -74,10 +73,7 @@ export class InMemoryCacheClass extends StorageCache implements ICache { private _isExpired(key: string): boolean { const text: string | null = CacheObject.getItem(key); - asserts(text !== null, { - name: STORAGE_CACHE_EXCEPTION, - message: 'item from storage is null', - }); + assert(text !== null, CacheErrorCode.NoCacheItem, `Key: ${key}`); const item: CacheItem = JSON.parse(text); if (getCurrTime() >= item.expires) { return true; @@ -96,10 +92,7 @@ export class InMemoryCacheClass extends StorageCache implements ICache { this.cacheList[listIdx].removeItem(prefixedKey); // decrease the current size of the cache const item = CacheObject.getItem(prefixedKey); - asserts(item !== null, { - name: STORAGE_CACHE_EXCEPTION, - message: 'item from storage is null', - }); + assert(item !== null, CacheErrorCode.NoCacheItem, `Key: ${prefixedKey}`); this._decreaseCurSizeInBytes(JSON.parse(item).byteSize); // finally remove the item from memory CacheObject.removeItem(prefixedKey); diff --git a/packages/core/src/Cache/Utils/CacheList.ts b/packages/core/src/Cache/Utils/CacheList.ts index c553b24e57f..596601c0b0c 100644 --- a/packages/core/src/Cache/Utils/CacheList.ts +++ b/packages/core/src/Cache/Utils/CacheList.ts @@ -1,8 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { asserts } from '../../Util/errors/AssertError'; -import { CACHE_LIST_EXCEPTION } from '../../Util/Constants'; +import { assert, CacheErrorCode } from './errorHelpers'; class DoubleLinkedNode { key: string; @@ -56,10 +55,7 @@ export default class CacheList { this.head.nextNode = node; node.nextNode = tmp; node.prevNode = this.head; - asserts(tmp !== null, { - name: CACHE_LIST_EXCEPTION, - message: 'previous node is null', - }); + assert(tmp !== null, CacheErrorCode.NullPreviousNode); tmp.prevNode = node; this.length = this.length + 1; @@ -71,14 +67,8 @@ export default class CacheList { * @param node */ private removeNode(node: DoubleLinkedNode): void { - asserts(node.prevNode !== null, { - name: CACHE_LIST_EXCEPTION, - message: 'previous node is null', - }); - asserts(node.nextNode !== null, { - name: CACHE_LIST_EXCEPTION, - message: 'nextNode node is null', - }); + assert(node.prevNode !== null, CacheErrorCode.NullPreviousNode); + assert(node.nextNode !== null, CacheErrorCode.NullNextNode); node.prevNode.nextNode = node.nextNode; node.nextNode.prevNode = node.prevNode; @@ -121,10 +111,7 @@ export default class CacheList { * @return the LAST Recently Visited key */ public getLastItem(): string { - asserts(this.tail.prevNode !== null, { - name: CACHE_LIST_EXCEPTION, - message: 'previous node is null', - }); + assert(this.tail.prevNode !== null, CacheErrorCode.NullPreviousNode); return this.tail.prevNode.key; } diff --git a/packages/core/src/Cache/Utils/errorHelpers.ts b/packages/core/src/Cache/Utils/errorHelpers.ts new file mode 100644 index 00000000000..ccb4b7fee05 --- /dev/null +++ b/packages/core/src/Cache/Utils/errorHelpers.ts @@ -0,0 +1,30 @@ +// 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 CacheErrorCode { + NoCacheItem = 'NoCacheItem', + NoCacheStorage = 'NoCacheStorage', + NullNextNode = 'NullNextNode', + NullPreviousNode = 'NullPreviousNode', +} + +const cacheErrorMap: AmplifyErrorMap = { + [CacheErrorCode.NoCacheItem]: { + message: 'Item not found in the cache storage.', + }, + [CacheErrorCode.NoCacheStorage]: { + message: 'Storage is not defined in the cache config.', + }, + [CacheErrorCode.NullNextNode]: { + message: 'Next node is null.', + }, + [CacheErrorCode.NullPreviousNode]: { + message: 'Previous node is null.', + }, +}; + +export const assert: AssertionFunction = + createAssertionFunction(cacheErrorMap); diff --git a/packages/core/src/Hub/index.ts b/packages/core/src/Hub/index.ts index 9bf7b10ffd5..9b3aa495eed 100644 --- a/packages/core/src/Hub/index.ts +++ b/packages/core/src/Hub/index.ts @@ -3,7 +3,7 @@ import { ConsoleLogger as Logger } from '../Logger'; import { NO_HUBCALLBACK_PROVIDED_EXCEPTION } from '../Util/Constants'; -import { AmplifyError } from '../Util/Errors'; +import { AmplifyError } from '../errors'; import { AmplifyChannel, AmplifyEventData, diff --git a/packages/core/src/I18n/errorHelpers.ts b/packages/core/src/I18n/errorHelpers.ts new file mode 100644 index 00000000000..051f89a62a4 --- /dev/null +++ b/packages/core/src/I18n/errorHelpers.ts @@ -0,0 +1,18 @@ +// 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 I18nErrorCode { + NotConfigured = 'NotConfigured', +} + +const i18nErrorMap: AmplifyErrorMap = { + [I18nErrorCode.NotConfigured]: { + message: 'i18n is not configured.', + }, +}; + +export const assert: AssertionFunction = + createAssertionFunction(i18nErrorMap); diff --git a/packages/core/src/I18n/index.ts b/packages/core/src/I18n/index.ts index 9c93fd2aa06..04262b74d4a 100644 --- a/packages/core/src/I18n/index.ts +++ b/packages/core/src/I18n/index.ts @@ -5,8 +5,7 @@ import { I18n as I18nClass } from './I18n'; import { ConsoleLogger as Logger } from '../Logger'; import { I18nOptions } from './types'; -import { asserts } from '../Util/errors/AssertError'; -import { I18N_EXCEPTION } from '../Util/Constants'; +import { assert, I18nErrorCode } from './errorHelpers'; const logger = new Logger('I18n'); @@ -15,7 +14,7 @@ let _i18n: I18nClass | null = null; /** * Export I18n APIs - * + * * @deprecated The I18n utility is on a deprecation path and will be removed in a future version of Amplify. */ export class I18n { @@ -46,7 +45,7 @@ export class I18n { * @static * @method * Create an instance of I18n for the library - * + * * @deprecated The I18n utility is on a deprecation path and will be removed in a future version of Amplify. */ static createInstance() { @@ -61,15 +60,13 @@ export class I18n { * @static @method * Explicitly setting language * @param {String} lang - * + * * @deprecated The I18n utility is on a deprecation path and will be removed in a future version of Amplify. */ static setLanguage(lang: string) { I18n.checkConfig(); - asserts(!!_i18n, { - name: I18N_EXCEPTION, - message: 'I18N is not configured', - }); + assert(!!_i18n, I18nErrorCode.NotConfigured); + return _i18n.setLanguage(lang); } @@ -78,17 +75,14 @@ export class I18n { * Get value * @param {String} key * @param {String} defVal - Default value - * + * * @deprecated The I18n utility is on a deprecation path and will be removed in a future version of Amplify. */ static get(key: string, defVal?: string) { if (!I18n.checkConfig()) { return typeof defVal === 'undefined' ? key : defVal; } - asserts(!!_i18n, { - name: I18N_EXCEPTION, - message: 'I18N is not configured', - }); + assert(!!_i18n, I18nErrorCode.NotConfigured); return _i18n.get(key, defVal); } @@ -99,7 +93,7 @@ export class I18n { * Add vocabularies for one language * @param {String} langurage - Language of the dictionary * @param {Object} vocabularies - Object that has key-value as dictionary entry - * + * * @deprecated The I18n utility is on a deprecation path and will be removed in a future version of Amplify. */ static putVocabulariesForLanguage( @@ -107,10 +101,7 @@ export class I18n { vocabularies: Record ) { I18n.checkConfig(); - asserts(!!_i18n, { - name: I18N_EXCEPTION, - message: 'I18N is not configured', - }); + assert(!!_i18n, I18nErrorCode.NotConfigured); return _i18n.putVocabulariesForLanguage(language, vocabularies); } @@ -121,15 +112,12 @@ export class I18n { * Add vocabularies for one language * @param {Object} vocabularies - Object that has language as key, * vocabularies of each language as value - * + * * @deprecated The I18n utility is on a deprecation path and will be removed in a future version of Amplify. */ static putVocabularies(vocabularies: Record) { I18n.checkConfig(); - asserts(!!_i18n, { - name: I18N_EXCEPTION, - message: 'I18N is not configured', - }); + assert(!!_i18n, I18nErrorCode.NotConfigured); return _i18n.putVocabularies(vocabularies); } diff --git a/packages/core/src/ServiceWorker/ServiceWorker.ts b/packages/core/src/ServiceWorker/ServiceWorker.ts index 8397bea30fe..7c282191041 100644 --- a/packages/core/src/ServiceWorker/ServiceWorker.ts +++ b/packages/core/src/ServiceWorker/ServiceWorker.ts @@ -1,23 +1,11 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with - * the License. A copy of the License is located at - * - * http://aws.amazon.com/apache2.0/ - * - * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ + import { ConsoleLogger as Logger } from '../Logger'; import { isBrowser } from '../Util/JS'; import { Amplify } from '../Amplify'; -import { asserts } from '../Util/errors/AssertError'; -import { AmplifyError } from '../Util/Errors'; -import { SERVICE_WORKER_EXCEPTION } from '../Util/Constants'; +import { AmplifyError } from '../errors'; +import { assert, ServiceWorkerErrorCode } from './errorHelpers'; /** * Provides a means to registering a service worker in the browser * and communicating with it via postMessage events. @@ -53,10 +41,10 @@ export class ServiceWorkerClass { * Get the currently active service worker */ get serviceWorker(): ServiceWorker { - asserts(this._serviceWorker !== undefined, { - name: SERVICE_WORKER_EXCEPTION, - message: 'Service Worker instance is undefined', - }); + assert( + this._serviceWorker !== undefined, + ServiceWorkerErrorCode.UndefinedInstance + ); return this._serviceWorker; } @@ -101,7 +89,7 @@ export class ServiceWorkerClass { this._logger.debug(`Service Worker Registration Failed ${error}`); return reject( new AmplifyError({ - name: SERVICE_WORKER_EXCEPTION, + name: ServiceWorkerErrorCode.Unavailable, message: 'Service Worker not available', underlyingError: error, }) @@ -110,7 +98,7 @@ export class ServiceWorkerClass { } else { return reject( new AmplifyError({ - name: SERVICE_WORKER_EXCEPTION, + name: ServiceWorkerErrorCode.Unavailable, message: 'Service Worker not available', }) ); @@ -130,17 +118,17 @@ export class ServiceWorkerClass { * - reject(Error) */ enablePush(publicKey: string) { - asserts(this._registration !== undefined, { - name: SERVICE_WORKER_EXCEPTION, - message: 'Service Worker registration is undefined', - }); + assert( + this._registration !== undefined, + ServiceWorkerErrorCode.UndefinedRegistration + ); this._publicKey = publicKey; return new Promise((resolve, reject) => { if (isBrowser()) { - asserts(this._registration !== undefined, { - name: SERVICE_WORKER_EXCEPTION, - message: 'Service Worker registration is undefined', - }); + assert( + this._registration !== undefined, + ServiceWorkerErrorCode.UndefinedRegistration + ); this._registration.pushManager.getSubscription().then(subscription => { if (subscription) { this._subscription = subscription; @@ -169,7 +157,7 @@ export class ServiceWorkerClass { } else { return reject( new AmplifyError({ - name: SERVICE_WORKER_EXCEPTION, + name: ServiceWorkerErrorCode.Unavailable, message: 'Service Worker not available', }) ); diff --git a/packages/core/src/ServiceWorker/errorHelpers.ts b/packages/core/src/ServiceWorker/errorHelpers.ts new file mode 100644 index 00000000000..b3663ca6da8 --- /dev/null +++ b/packages/core/src/ServiceWorker/errorHelpers.ts @@ -0,0 +1,26 @@ +// 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 ServiceWorkerErrorCode { + UndefinedInstance = 'UndefinedInstance', + UndefinedRegistration = 'UndefinedRegistration', + Unavailable = 'Unavailable', +} + +const serviceWorkerErrorMap: AmplifyErrorMap = { + [ServiceWorkerErrorCode.UndefinedInstance]: { + message: 'Service Worker instance is undefined.', + }, + [ServiceWorkerErrorCode.UndefinedRegistration]: { + message: 'Service Worker registration is undefined.', + }, + [ServiceWorkerErrorCode.Unavailable]: { + message: 'Service Worker not available.', + }, +}; + +export const assert: AssertionFunction = + createAssertionFunction(serviceWorkerErrorMap); diff --git a/packages/core/src/Util/Constants.ts b/packages/core/src/Util/Constants.ts index 9bf710249b7..53004c7bdc0 100644 --- a/packages/core/src/Util/Constants.ts +++ b/packages/core/src/Util/Constants.ts @@ -23,11 +23,5 @@ export const INTERNAL_AWS_APPSYNC_REALTIME_PUBSUB_PROVIDER = hasSymbol export const USER_AGENT_HEADER = 'x-amz-user-agent'; // Error exception code constants -export const AUTH_CONFING_EXCEPTION = 'AuthConfigException'; -export const CACHE_LIST_EXCEPTION = 'CacheListException'; -export const I18N_EXCEPTION = 'I18NException'; -export const SERVICE_WORKER_EXCEPTION = 'ServiceWorkerException'; -export const STORAGE_CACHE_EXCEPTION = 'StorageCacheException'; -export const APPLICATION_ID_EXCEPTION = 'ApplicationIdException'; export const NO_HUBCALLBACK_PROVIDED_EXCEPTION = 'NoHubcallbackProvidedException'; diff --git a/packages/core/src/Util/errors/AssertError.ts b/packages/core/src/Util/errors/AssertError.ts deleted file mode 100644 index bffda25c752..00000000000 --- a/packages/core/src/Util/errors/AssertError.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -import { AmplifyError } from '../Errors'; -import { ErrorParams } from '../../types'; - -export function asserts( - assertion: boolean, - errorParams: ErrorParams -): asserts assertion { - if (!assertion) throw new AmplifyError(errorParams); -} diff --git a/packages/core/src/adapterCore/error/AmplifyServerContextError.ts b/packages/core/src/adapterCore/error/AmplifyServerContextError.ts index 0702bddfddf..3ebf2733f7a 100644 --- a/packages/core/src/adapterCore/error/AmplifyServerContextError.ts +++ b/packages/core/src/adapterCore/error/AmplifyServerContextError.ts @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { AmplifyError } from '../../libraryUtils'; +import { AmplifyError } from '../../errors'; export class AmplifyServerContextError extends AmplifyError { constructor({ diff --git a/packages/core/src/Util/Errors.ts b/packages/core/src/errors/AmplifyError.ts similarity index 61% rename from packages/core/src/Util/Errors.ts rename to packages/core/src/errors/AmplifyError.ts index 6ee1a8da9df..9d1c6759bf1 100644 --- a/packages/core/src/Util/Errors.ts +++ b/packages/core/src/errors/AmplifyError.ts @@ -1,19 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { ErrorParams } from '../types/errors'; +import { AmplifyErrorParams } from '../types/errors'; -export function missingConfig(name: string) { - return new Error('Missing config value of ' + name); -} -export function invalidParameter(name: string) { - return new Error('Invalid parameter value of ' + name); -} - -export enum AmplifyErrorString { - UNKNOWN = 'UnknownError', - PLATFORM_NOT_SUPPORTED_ERROR = 'PlatformNotSupportedError', -} export class AmplifyError extends Error { underlyingError?: Error | unknown; recoverySuggestion?: string; @@ -30,7 +19,7 @@ export class AmplifyError extends Error { name, recoverySuggestion, underlyingError, - }: ErrorParams) { + }: AmplifyErrorParams) { super(message); this.name = name; @@ -43,8 +32,3 @@ export class AmplifyError extends Error { Object.setPrototypeOf(this, AmplifyError.prototype); } } - -export const PlatformNotSupportedError = new AmplifyError({ - name: AmplifyErrorString.PLATFORM_NOT_SUPPORTED_ERROR, - message: 'Function not supported on current platform', -}); diff --git a/packages/core/src/errors/PlatformNotSupportedError.ts b/packages/core/src/errors/PlatformNotSupportedError.ts new file mode 100644 index 00000000000..35fe9eda689 --- /dev/null +++ b/packages/core/src/errors/PlatformNotSupportedError.ts @@ -0,0 +1,14 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { AmplifyErrorCode } from '../types'; +import { AmplifyError } from './AmplifyError'; + +export class PlatformNotSupportedError extends AmplifyError { + constructor() { + super({ + name: AmplifyErrorCode.PlatformNotSupported, + message: 'Function not supported on current platform', + }); + } +} diff --git a/packages/core/src/errors/createAssertionFunction.ts b/packages/core/src/errors/createAssertionFunction.ts new file mode 100644 index 00000000000..1e2e7f0b8aa --- /dev/null +++ b/packages/core/src/errors/createAssertionFunction.ts @@ -0,0 +1,23 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { AmplifyErrorMap, AssertionFunction } from '../types'; +import { AmplifyError } from './AmplifyError'; + +export const createAssertionFunction = + ( + errorMap: AmplifyErrorMap, + AssertionError = AmplifyError + ): AssertionFunction => + (assertion, name, additionalContext) => { + const { message, recoverySuggestion } = errorMap[name]; + if (!assertion) { + throw new AssertionError({ + name, + message: additionalContext + ? `${message} ${additionalContext}` + : message, + recoverySuggestion, + }); + } + }; diff --git a/packages/core/src/errors/index.ts b/packages/core/src/errors/index.ts new file mode 100644 index 00000000000..6eb0da4cfe8 --- /dev/null +++ b/packages/core/src/errors/index.ts @@ -0,0 +1,6 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +export { AmplifyError } from './AmplifyError'; +export { createAssertionFunction } from './createAssertionFunction'; +export { PlatformNotSupportedError } from './PlatformNotSupportedError'; diff --git a/packages/core/src/libraryUtils.ts b/packages/core/src/libraryUtils.ts index 7944806c65e..1e9b2a96487 100644 --- a/packages/core/src/libraryUtils.ts +++ b/packages/core/src/libraryUtils.ts @@ -32,7 +32,7 @@ export { export { decodeJWT, assertTokenProviderConfig, - assertIdentityPooIdConfig, + assertIdentityPoolIdConfig, assertOAuthConfig, } from './singleton/Auth/utils'; export { isTokenExpired } from './singleton/Auth'; @@ -92,14 +92,18 @@ export { urlSafeDecode, urlSafeEncode, } from './Util'; -export { asserts } from './Util/errors/AssertError'; export { - invalidParameter, - missingConfig, AmplifyError, - AmplifyErrorString, -} from './Util/Errors'; -export { ErrorParams, AmplifyErrorMap, ServiceError } from './types'; + PlatformNotSupportedError, + createAssertionFunction, +} from './errors'; +export { + AmplifyErrorCode, + AmplifyErrorMap, + AmplifyErrorParams, + AssertionFunction, + ServiceError, +} from './types'; export { INTERNAL_AWS_APPSYNC_REALTIME_PUBSUB_PROVIDER, USER_AGENT_HEADER, diff --git a/packages/core/src/providers/pinpoint/apis/record.ts b/packages/core/src/providers/pinpoint/apis/record.ts index 3453bb022c1..cd1c33cedc9 100644 --- a/packages/core/src/providers/pinpoint/apis/record.ts +++ b/packages/core/src/providers/pinpoint/apis/record.ts @@ -12,7 +12,7 @@ import { } from '../utils/constants'; import { updateEndpoint } from './updateEndpoint'; import { getEventBuffer } from '../utils/getEventBuffer'; -import { AmplifyError } from '../../../libraryUtils'; +import { AmplifyError } from '../../../errors'; // TODO(v6) Refactor when we add support for session tracking & `autoTrack` let session: PinpointSession; diff --git a/packages/core/src/singleton/Auth/utils/errorHelpers.ts b/packages/core/src/singleton/Auth/utils/errorHelpers.ts new file mode 100644 index 00000000000..dfa45ecaacf --- /dev/null +++ b/packages/core/src/singleton/Auth/utils/errorHelpers.ts @@ -0,0 +1,37 @@ +// 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 AuthConfigurationErrorCode { + AuthTokenConfigException = 'AuthTokenConfigException', + AuthUserPoolAndIdentityPoolException = 'AuthUserPoolAndIdentityPoolException', + InvalidIdentityPoolIdException = 'InvalidIdentityPoolIdException', + OAuthNotConfigureException = 'OAuthNotConfigureException', +} + +const authConfigurationErrorMap: AmplifyErrorMap = { + [AuthConfigurationErrorCode.AuthTokenConfigException]: { + message: 'Auth Token Provider not configured.', + recoverySuggestion: 'Make sure to call Amplify.configure in your app.', + }, + [AuthConfigurationErrorCode.AuthUserPoolAndIdentityPoolException]: { + message: 'Auth UserPool or IdentityPool not configured.', + recoverySuggestion: + 'Make sure to call Amplify.configure in your app with UserPoolId and IdentityPoolId.', + }, + [AuthConfigurationErrorCode.InvalidIdentityPoolIdException]: { + message: 'Invalid identity pool id provided.', + recoverySuggestion: + 'Make sure a valid identityPoolId is given in the config.', + }, + [AuthConfigurationErrorCode.OAuthNotConfigureException]: { + message: 'oauth param not configured.', + recoverySuggestion: + 'Make sure to call Amplify.configure with oauth parameter in your app.', + }, +}; + +export const assert: AssertionFunction = + createAssertionFunction(authConfigurationErrorMap); diff --git a/packages/core/src/singleton/Auth/utils/index.ts b/packages/core/src/singleton/Auth/utils/index.ts index 0164a0df220..718d2d30d14 100644 --- a/packages/core/src/singleton/Auth/utils/index.ts +++ b/packages/core/src/singleton/Auth/utils/index.ts @@ -1,6 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { asserts } from '../../../Util/errors/AssertError'; +import { AuthConfigurationErrorCode, assert } from './errorHelpers'; import { AuthConfig, @@ -30,11 +30,10 @@ export function assertTokenProviderConfig( !!cognitoConfig.userPoolClientId && !!cognitoConfig.userPoolClientId; } - return asserts(assertionValid, { - name: 'AuthTokenConfigException', - message: 'Auth Token Provider not configured', - recoverySuggestion: 'Make sure to call Amplify.configure in your app', - }); + return assert( + assertionValid, + AuthConfigurationErrorCode.AuthTokenConfigException + ); } export function assertOAuthConfig( @@ -46,15 +45,13 @@ export function assertOAuthConfig( !!cognitoConfig?.loginWith?.oauth?.redirectSignIn && !!cognitoConfig?.loginWith?.oauth?.responseType; - return asserts(validOAuthConfig, { - name: 'OAuthNotConfigureException', - message: 'oauth param not configured', - recoverySuggestion: - 'Make sure to call Amplify.configure with oauth parameter in your app', - }); + return assert( + validOAuthConfig, + AuthConfigurationErrorCode.OAuthNotConfigureException + ); } -export function assertIdentityPooIdConfig( +export function assertIdentityPoolIdConfig( cognitoConfig?: StrictUnion< | CognitoUserPoolConfig | CognitoUserPoolAndIdentityPoolConfig @@ -62,25 +59,21 @@ export function assertIdentityPooIdConfig( > ): asserts cognitoConfig is CognitoIdentityPoolConfig { const validConfig = !!cognitoConfig?.identityPoolId; - return asserts(validConfig, { - name: 'InvalidIdentityPoolIdException', - message: 'Invalid identity pool id provided.', - recoverySuggestion: - 'Make sure a valid identityPoolId is given in the config.', - }); + return assert( + validConfig, + AuthConfigurationErrorCode.InvalidIdentityPoolIdException + ); } -function assertUserPoolAndIdentityPooConfig( +function assertUserPoolAndIdentityPoolConfig( authConfig: AuthConfig ): asserts authConfig is AuthUserPoolAndIdentityPoolConfig { const validConfig = !!authConfig?.Cognito.identityPoolId && !!authConfig?.Cognito.userPoolId; - return asserts(validConfig, { - name: 'AuthUserPoolAndIdentityPoolException', - message: 'Auth UserPool and IdentityPool not configured', - recoverySuggestion: - 'Make sure to call Amplify.configure in your app with UserPoolId and IdentityPoolId', - }); + return assert( + validConfig, + AuthConfigurationErrorCode.AuthUserPoolAndIdentityPoolException + ); } export function decodeJWT(token: string): JWT { diff --git a/packages/core/src/storage/DefaultStorage.native.ts b/packages/core/src/storage/DefaultStorage.native.ts index 162c60fdf96..add037c1366 100644 --- a/packages/core/src/storage/DefaultStorage.native.ts +++ b/packages/core/src/storage/DefaultStorage.native.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { AsyncStorageStatic } from '@react-native-async-storage/async-storage'; -import { AmplifyError } from '../libraryUtils'; +import { AmplifyError } from '../errors'; import { KeyValueStorageInterface } from '../types'; const ASYNC_STORAGE_MODULE = '@react-native-async-storage/async-storage'; diff --git a/packages/core/src/storage/KeyValueStorage.ts b/packages/core/src/storage/KeyValueStorage.ts index 03d1cd55275..45290629774 100644 --- a/packages/core/src/storage/KeyValueStorage.ts +++ b/packages/core/src/storage/KeyValueStorage.ts @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { PlatformNotSupportedError } from '../Util/Errors'; +import { PlatformNotSupportedError } from '../errors'; import { KeyValueStorageInterface } from '../types'; /** @@ -21,7 +21,7 @@ export class KeyValueStorage implements KeyValueStorageInterface { * @returns {string} value that was set */ async setItem(key: string, value: string) { - if (!this.storage) throw PlatformNotSupportedError; + if (!this.storage) throw new PlatformNotSupportedError(); this.storage.setItem(key, value); } @@ -32,7 +32,7 @@ export class KeyValueStorage implements KeyValueStorageInterface { * @returns {string} the data item */ async getItem(key: string) { - if (!this.storage) throw PlatformNotSupportedError; + if (!this.storage) throw new PlatformNotSupportedError(); return this.storage.getItem(key); } @@ -42,7 +42,7 @@ export class KeyValueStorage implements KeyValueStorageInterface { * @returns {string} value - value that was deleted */ async removeItem(key: string) { - if (!this.storage) throw PlatformNotSupportedError; + if (!this.storage) throw new PlatformNotSupportedError(); this.storage.removeItem(key); } @@ -51,7 +51,7 @@ export class KeyValueStorage implements KeyValueStorageInterface { * @returns {string} nothing */ async clear() { - if (!this.storage) throw PlatformNotSupportedError; + if (!this.storage) throw new PlatformNotSupportedError(); this.storage.clear(); } } diff --git a/packages/core/src/types/errors.ts b/packages/core/src/types/errors.ts index f01054c0055..845f8505435 100644 --- a/packages/core/src/types/errors.ts +++ b/packages/core/src/types/errors.ts @@ -1,14 +1,19 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -export type ErrorParams = { +export enum AmplifyErrorCode { + PlatformNotSupported = 'PlatformNotSupported', + Unknown = 'Unknown', +} + +export type AmplifyErrorParams = { message: string; - name: string; + name: ErrorCode; recoverySuggestion?: string; underlyingError?: Error | unknown; }; -export type AmplifyErrorMap = { +export type AmplifyErrorMap = { [name in ErrorCode]: { message: string; recoverySuggestion?: string; @@ -19,3 +24,9 @@ export type ServiceError = { name: string; message: string; }; + +export type AssertionFunction = ( + assertion: boolean, + name: ErrorCode, + additionalContext?: string +) => asserts assertion; diff --git a/packages/storage/src/errors/CanceledError.ts b/packages/storage/src/errors/CanceledError.ts index 9c9fb654790..128ed72e089 100644 --- a/packages/storage/src/errors/CanceledError.ts +++ b/packages/storage/src/errors/CanceledError.ts @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { ErrorParams } from '@aws-amplify/core/internals/utils'; +import { AmplifyErrorParams } from '@aws-amplify/core/internals/utils'; import { StorageError } from './StorageError'; /** @@ -11,7 +11,7 @@ import { StorageError } from './StorageError'; * @internal */ export class CanceledError extends StorageError { - constructor(params: ErrorParams) { + constructor(params: AmplifyErrorParams) { super(params); // TODO: Delete the following 2 lines after we change the build target to >= es2015 diff --git a/packages/storage/src/errors/StorageError.ts b/packages/storage/src/errors/StorageError.ts index 90a91e21736..0903c8eb835 100644 --- a/packages/storage/src/errors/StorageError.ts +++ b/packages/storage/src/errors/StorageError.ts @@ -1,9 +1,12 @@ // 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 StorageError extends AmplifyError { - constructor(params: ErrorParams) { + constructor(params: AmplifyErrorParams) { super(params); // TODO: Delete the following 2 lines after we change the build target to >= es2015 diff --git a/packages/storage/src/providers/s3/utils/client/utils/serializeHelpers.ts b/packages/storage/src/providers/s3/utils/client/utils/serializeHelpers.ts index 5d66b7d14ee..29f5b4943e4 100644 --- a/packages/storage/src/providers/s3/utils/client/utils/serializeHelpers.ts +++ b/packages/storage/src/providers/s3/utils/client/utils/serializeHelpers.ts @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { extendedEncodeURIComponent } from '@aws-amplify/core/internals/aws-client-utils'; -import { AmplifyErrorString } from '@aws-amplify/core/internals/utils'; +import { AmplifyErrorCode } from '@aws-amplify/core/internals/utils'; import { StorageError } from '../../../../../errors/StorageError'; /** @@ -81,7 +81,7 @@ export function validateS3RequiredParameter( ): asserts assertion { if (!assertion) { throw new StorageError({ - name: AmplifyErrorString.UNKNOWN, + name: AmplifyErrorCode.Unknown, message: 'An unknown error has ocurred.', underlyingError: new TypeError( `Expected a non-null value for S3 parameter ${paramName}`