Skip to content

Commit 234ecbf

Browse files
committed
fix: return fallback if value cannot be parsed
If there is a fallback we should handle this error more gracefully. We report it in the console, but return the fallback if provided. Otherwise we just throw as before. Signed-off-by: Ferdinand Thiessen <opensource@fthiessen.de>
1 parent e78d684 commit 234ecbf

3 files changed

Lines changed: 42 additions & 1 deletion

File tree

eslint.config.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,12 @@
66
import { recommendedLibrary } from '@nextcloud/eslint-config'
77
import { defineConfig } from 'eslint/config'
88

9-
export default defineConfig([...recommendedLibrary])
9+
export default defineConfig([
10+
...recommendedLibrary,
11+
{
12+
rules: {
13+
// this is quite a lowlevel library without dependencies - so no dependency on the logger
14+
'no-console': 'off',
15+
},
16+
},
17+
])

lib/index.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@ export function loadState<T>(app: string, key: string, fallback?: T): T {
3131
window._nc_initial_state.set(selector, parsedValue)
3232
return parsedValue
3333
} catch (error) {
34+
console.error('[@nextcloud/initial-state] Could not parse initial state', { key, app, error })
35+
36+
if (fallback !== undefined) {
37+
return fallback
38+
}
3439
throw new Error(`Could not parse initial state ${key} of ${app}`, { cause: error })
3540
}
3641
}

test/index.test.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,3 +46,31 @@ test('returns cached value with consequent calls', () => {
4646

4747
expect(JSON.parse).toHaveBeenCalledTimes(1)
4848
})
49+
50+
test('throws if state cannot be parsed and no fallback is provided', () => {
51+
const errorLog = vi.spyOn(console, 'error')
52+
errorLog.mockImplementationOnce(() => {})
53+
54+
appendInput('app', 'key', 'value')
55+
const spy = vi.spyOn(JSON, 'parse')
56+
spy.mockImplementationOnce(() => {
57+
throw new Error('mocked parsing exception')
58+
})
59+
60+
expect(() => loadState('app', 'key')).toThrowError('Could not parse initial state key of app')
61+
expect(errorLog).toHaveBeenCalledOnce()
62+
})
63+
64+
test('returns fallback if state cannot be parsed but fallback is provided', () => {
65+
const errorLog = vi.spyOn(console, 'error')
66+
errorLog.mockImplementationOnce(() => {})
67+
68+
appendInput('app', 'key', 'value')
69+
const spy = vi.spyOn(JSON, 'parse')
70+
spy.mockImplementationOnce(() => {
71+
throw new Error('mocked parsing exception')
72+
})
73+
74+
expect(loadState('app', 'key', 'fallback')).toBe('fallback')
75+
expect(errorLog).toHaveBeenCalledOnce()
76+
})

0 commit comments

Comments
 (0)