Skip to content

Commit

Permalink
Capture JSON parsing errors in chat-slice.ts (#859)
Browse files Browse the repository at this point in the history
  • Loading branch information
fredrikekelund authored Jan 30, 2025
1 parent ef24d16 commit 4dce063
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/stores/chat-slice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ const fetchAssistant = createAsyncThunk(
},
( error, data, headers ) => {
if ( error ) {
Sentry.captureException( error );
return reject( error );
}
return resolve( { data, headers } );
Expand Down Expand Up @@ -191,6 +192,17 @@ const getInitialState = (): ChatState => {
const storedMessages = localStorage.getItem( LOCAL_STORAGE_CHAT_MESSAGES_KEY );
const storedChatIds = localStorage.getItem( LOCAL_STORAGE_CHAT_API_IDS_KEY );

let parsedStoredMessages: ChatState[ 'messagesDict' ] = {};
let parsedStoredChatIds: ChatState[ 'chatApiIdDict' ] = {};

try {
parsedStoredMessages = storedMessages ? JSON.parse( storedMessages ) : {};
parsedStoredChatIds = storedChatIds ? JSON.parse( storedChatIds ) : {};
} catch ( error ) {
Sentry.captureException( error );
console.error( error );
}

return {
currentURL: '',
pluginListDict: {},
Expand All @@ -203,8 +215,8 @@ const getInitialState = (): ChatState => {
os: window.appGlobals?.platform || '',
availableEditors: [],
siteName: '',
messagesDict: storedMessages ? JSON.parse( storedMessages ) : {},
chatApiIdDict: storedChatIds ? JSON.parse( storedChatIds ) : {},
messagesDict: parsedStoredMessages,
chatApiIdDict: parsedStoredChatIds,
chatInputBySite: {},
isLoadingDict: {},
promptUsageDict: {},
Expand Down
17 changes: 17 additions & 0 deletions src/stores/tests/chat-slice.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,23 @@ describe( 'chat-slice', () => {
);
expect( storedChatIds[ instanceId ] ).toBe( 'chatcmpl-123' );
} );

it( 'should handle invalid JSON in localStorage gracefully', () => {
const consoleErrorSpy = jest.spyOn( console, 'error' );

localStorage.setItem( LOCAL_STORAGE_CHAT_MESSAGES_KEY, 'invalid json' );
localStorage.setItem( LOCAL_STORAGE_CHAT_API_IDS_KEY, '{also invalid}' );

jest.isolateModules( () => {
const { store } = require( 'src/stores' );

const state = store.getState();
expect( state.chat.messagesDict ).toEqual( {} );
expect( state.chat.chatApiIdDict ).toEqual( {} );
} );

expect( consoleErrorSpy ).toHaveBeenCalledTimes( 1 );
} );
} );

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

0 comments on commit 4dce063

Please sign in to comment.