diff --git a/flagsmith-core.ts b/flagsmith-core.ts index 94062af..7440607 100644 --- a/flagsmith-core.ts +++ b/flagsmith-core.ts @@ -79,7 +79,7 @@ const Flagsmith = class { } } - getFlags = () => { + getFlags = ({ callOnErrorWhenRequestFails = false }: { callOnErrorWhenRequestFails?: boolean } = {}) => { let { api, evaluationContext } = this; this.log("Get Flags") this.isLoading = true; @@ -210,12 +210,24 @@ const Flagsmith = class { return handleResponse(res?.[0] as IFlagsmithResponse | null) }).catch(({ message }) => { const error = new Error(message) - return Promise.reject(error) + + if (callOnErrorWhenRequestFails) { + this.onError?.(error) + } else { + return Promise.reject(error) + } }); } else { return this.getJSON(api + "flags/") .then((res) => { return handleResponse({ flags: res as IFlagsmithResponse['flags'], traits:undefined }) + }).catch((error) => { + + if (callOnErrorWhenRequestFails) { + this.onError?.(error) + } else { + throw error + } }) } }; @@ -479,9 +491,8 @@ const Flagsmith = class { } if (shouldFetchFlags) { // We want to resolve init since we have cached flags - this.getFlags().catch((e) => { - this.log("Exception fetching cached logs", e); - }); + + this.getFlags({ callOnErrorWhenRequestFails: true }) } } else { if (!preventFetch) { diff --git a/test/init.test.ts b/test/init.test.ts index 85f1bab..c547ef1 100644 --- a/test/init.test.ts +++ b/test/init.test.ts @@ -1,4 +1,5 @@ // Sample test +import { waitFor } from '@testing-library/react'; import { defaultState, environmentID, getFlagsmith, getStateToCheck, identityState } from './test-constants'; import { promises as fs } from 'fs' @@ -149,17 +150,24 @@ describe('Flagsmith.init', () => { })}), ) }); - test('should not reject when the API cannot be reached but the cache is populated', async () => { + test('should not reject but call onError, when the API cannot be reached with the cache populated', async () => { + const onError = jest.fn() const { flagsmith, initConfig, AsyncStorage } = getFlagsmith({ cacheFlags: true, fetch: async () => { return Promise.resolve({ text: () => Promise.resolve('Mocked fetch error'), ok: false, status: 401 }); }, + onError, }); await AsyncStorage.setItem('BULLET_TRAIN_DB', JSON.stringify(defaultState)); await flagsmith.init(initConfig); expect(getStateToCheck(flagsmith.getState())).toEqual(defaultState); + + await waitFor(() => { + expect(onError).toHaveBeenCalledTimes(1) + expect(onError).toHaveBeenCalledWith(new Error('Mocked fetch error')) + }) }) test('should not reject when the API cannot be reached but default flags are set', async () => { const { flagsmith, initConfig } = getFlagsmith({