Skip to content

Commit

Permalink
fix: add cookie storage logs (#778)
Browse files Browse the repository at this point in the history
  • Loading branch information
Mercy811 committed Jun 17, 2024
1 parent 0bc7f95 commit 743b9c0
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
9 changes: 5 additions & 4 deletions packages/analytics-client-common/src/storage/cookie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@ export class CookieStorage<T> implements Storage<T> {
try {
value = decodeURIComponent(atob(value));
} catch {
// value not encoded
console.error(`Amplitude Logger [Error]: Failed to decode cookie value for key: ${key}, value: ${value}`);
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return JSON.parse(value);
} catch {
/* istanbul ignore next */
console.error(`Amplitude Logger [Error]: Failed to parse cookie value for key: ${key}, value: ${value}`);
return undefined;
}
}
Expand Down Expand Up @@ -87,8 +87,9 @@ export class CookieStorage<T> implements Storage<T> {
if (globalScope) {
globalScope.document.cookie = str;
}
} catch {
//
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error(`Amplitude Logger [Error]: Failed to set cookie for key: ${key}. Error: ${errorMessage}`);
}
}

Expand Down
21 changes: 21 additions & 0 deletions packages/analytics-client-common/test/storage/cookies.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,27 @@ describe('cookies', () => {
expect(await cookies.get('hello')).toBe(undefined);
await cookies.remove('hello');
});

test.each([new Error('Simulated error'), 'Simulated error'])(
'logs an error message when setting a cookie fails',
async (error) => {
console.error = jest.fn();
jest.spyOn(global, 'btoa').mockImplementation(() => {
throw error;
});

const cookies = new CookieStorage();
await cookies.set('hello', 'world');

expect(console.error).toHaveBeenCalledWith(
expect.stringContaining(
`Amplitude Logger [Error]: Failed to set cookie for key: hello. Error: Simulated error`,
),
);

jest.restoreAllMocks();
},
);
});

describe('remove', () => {
Expand Down

0 comments on commit 743b9c0

Please sign in to comment.