From 7fe3167e978b6e76ca87b227917d56f85809b58a Mon Sep 17 00:00:00 2001 From: Koen Kanters Date: Sat, 19 Sep 2020 10:59:12 +0200 Subject: [PATCH] Fix crash when saving state.json fails. #4388 --- lib/state.js | 7 ++++++- test/bridge.test.js | 1 - test/controller.test.js | 9 +++++++++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/lib/state.js b/lib/state.js index a54828c31..301c2217d 100644 --- a/lib/state.js +++ b/lib/state.js @@ -58,7 +58,12 @@ class State { if (settings.get().advanced.cache_state_persistent) { logger.debug(`Saving state to file ${this.file}`); const json = stringify(this.state, null, 4); - fs.writeFileSync(this.file, json, 'utf8'); + try { + fs.writeFileSync(this.file, json, 'utf8'); + } catch (e) { + console.log(e.message); + logger.error(`Failed to write state to '${this.file}' (${e.message})`); + } } else { logger.debug(`Not saving state`); } diff --git a/test/bridge.test.js b/test/bridge.test.js index 2cd3247f8..85ecbc854 100644 --- a/test/bridge.test.js +++ b/test/bridge.test.js @@ -469,7 +469,6 @@ describe('Bridge', () => { MQTT.publish.mockClear(); MQTT.events.message('zigbee2mqtt/bridge/request/device/rename', stringify({from: 'bulb', to: 'bulb_new_name/1'})); await flushPromises(); - console.log(MQTT.publish.mock.calls); expect(MQTT.publish).toHaveBeenCalledWith( 'zigbee2mqtt/bridge/response/device/rename', stringify({"data":{},"status":"error","error":`Friendly name cannot end with a "/DIGIT" ('bulb_new_name/1')`}), diff --git a/test/controller.test.js b/test/controller.test.js index e766e9ae0..9c151cfaf 100644 --- a/test/controller.test.js +++ b/test/controller.test.js @@ -551,6 +551,15 @@ describe('Controller', () => { expect(data.stateExists()).toBeFalsy(); }); + it('Shouldnt crash when it cannot save state', async () => { + data.removeState(); + await controller.start(); + logger.error.mockClear(); + controller.state.file = "/"; + await controller.state.save(); + expect(logger.error).toHaveBeenCalledWith(`Failed to write state to '/' (EISDIR: illegal operation on a directory, open '/')`); + }); + it('Publish should not cache when set', async () => { settings.set(['advanced', 'cache_state'], false); data.writeEmptyState();