From 45f2d82f597d034da59dffb140f5701c8f98757a Mon Sep 17 00:00:00 2001 From: horike37 Date: Tue, 1 Nov 2016 05:02:29 +0900 Subject: [PATCH] Add Catch Errors for slstats --- lib/plugins/slstats/slstats.js | 23 ++++++++++++++--------- lib/plugins/slstats/tests/slstats.js | 18 ++++++++++++++++++ 2 files changed, 32 insertions(+), 9 deletions(-) diff --git a/lib/plugins/slstats/slstats.js b/lib/plugins/slstats/slstats.js index cc13b397b..52de89092 100644 --- a/lib/plugins/slstats/slstats.js +++ b/lib/plugins/slstats/slstats.js @@ -38,17 +38,22 @@ class SlStats { const statsDisabledFilePath = path.join(serverlessDirPath, 'stats-disabled'); const statsEnabledFilePath = path.join(serverlessDirPath, 'stats-enabled'); - if (this.options.enable && !this.options.disable) { - if (this.serverless.utils.fileExistsSync(statsDisabledFilePath)) { - fse.renameSync(statsDisabledFilePath, statsEnabledFilePath); + try { + if (this.options.enable && !this.options.disable) { + if (fse.lstatSync(statsDisabledFilePath).isFile()) { + fse.renameSync(statsDisabledFilePath, statsEnabledFilePath); + } + this.serverless.cli.log('Stats successfully enabled'); } - this.serverless.cli.log('Stats successfully enabled'); - } - if (this.options.disable && !this.options.enable) { - if (this.serverless.utils.fileExistsSync(statsEnabledFilePath)) { - fse.renameSync(statsEnabledFilePath, statsDisabledFilePath); + if (this.options.disable && !this.options.enable) { + if (fse.lstatSync(statsEnabledFilePath).isFile()) { + fse.renameSync(statsEnabledFilePath, statsDisabledFilePath); + } + this.serverless.cli.log('Stats successfully disabled'); } - this.serverless.cli.log('Stats successfully disabled'); + } catch (e) { + throw new this.serverless.classes + .Error(`slstats failed. The following message: ${e.message}`); } } } diff --git a/lib/plugins/slstats/tests/slstats.js b/lib/plugins/slstats/tests/slstats.js index f01c22393..c070f9aa5 100644 --- a/lib/plugins/slstats/tests/slstats.js +++ b/lib/plugins/slstats/tests/slstats.js @@ -82,6 +82,24 @@ describe('SlStats', () => { ).to.equal(false); }); + it('should throw error if the stats file is not exists', () => { + // create a stats-disabled file + serverless.utils.writeFileSync( + path.join(serverlessDirPath, 'stats-error-file'), + 'some content' + ); + + slStats.options = { enable: true }; + + expect(() => slStats.toggleStats()).to.throw(); + expect( + serverless.utils.fileExistsSync(path.join(serverlessDirPath, 'stats-enabled')) + ).to.equal(false); + expect( + serverless.utils.fileExistsSync(path.join(serverlessDirPath, 'stats-disabled')) + ).to.equal(false); + }); + afterEach(() => { // recover the homeDir process.env.HOME = homeDir;