From d53e1330f507a68440e6c63fb2806fbcfffa7c42 Mon Sep 17 00:00:00 2001 From: Koen Kanters Date: Wed, 11 Sep 2019 21:42:44 +0200 Subject: [PATCH] Improve error message when reading invalid YAML file. --- lib/util/yaml.js | 18 +++++++++++++++++- test/settings.test.js | 27 +++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/lib/util/yaml.js b/lib/util/yaml.js index b493e6d9..9d2ab8a4 100644 --- a/lib/util/yaml.js +++ b/lib/util/yaml.js @@ -2,7 +2,23 @@ const yaml = require('js-yaml'); const fs = require('fs'); function read(file) { - return yaml.safeLoad(fs.readFileSync(file, 'utf8')); + try { + return yaml.safeLoad(fs.readFileSync(file, 'utf8')); + } catch (error) { + if (error.name === 'YAMLException') { + error.message = + `\n\n\n` + + `\t====================================================================\n` + + `\tYour YAML file '${file}' is invalid\n` + + `\tUse e.g. https://jsonformatter.org/yaml-validator to find and fix the issue.\n` + + `\t====================================================================\n` + + `\n\n` + + error.message; + } + + + throw error; + } } function readIfExists(file) { diff --git a/test/settings.test.js b/test/settings.test.js index 088d7810..62940bcb 100644 --- a/test/settings.test.js +++ b/test/settings.test.js @@ -394,4 +394,31 @@ describe('Settings', () => { settings.banDevice('0x1234'); expect(settings.get().ban).toStrictEqual(['0x123', '0x1234']); }); + + it('Should throw error when yaml file is invalid', () => { + fs.writeFileSync(configurationFile, ` + good: 9 + \t wrong + `) + + let error; + try { + settings._reRead(); + } catch (e) { + error = e; + } + + expect(error.message).toContain(`Your YAML file '${configurationFile}' is invalid`); + }); + + it('Should throw error when yaml file does not exist', () => { + let error; + try { + settings._reRead(); + } catch (e) { + error = e; + } + + expect(error.message).toContain(`no such file or directory, open`); + }); });