From e5aef9ff32d52730315cd28225ecfa49b7f43611 Mon Sep 17 00:00:00 2001 From: Anton Medvedev Date: Thu, 9 Jan 2020 12:03:01 +0300 Subject: [PATCH] Add code snippet to error message --- index.js | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/index.js b/index.js index c6cffdd..1971f2d 100755 --- a/index.js +++ b/index.js @@ -101,15 +101,17 @@ function handle(input) { function apply(json) { - let output - - try { - output = args.reduce(reduce, json) - } catch (e) { - if (e !== std.skip) { - throw e - } else { - return + let output = json + + for (let [i, code] of args.entries()) { + try { + output = reduce(output, code) + } catch (e) { + if (e === std.skip) { + return + } + stderr.write(`${snippet(i, code)}\n${e.stack || e}\n`) + process.exit(1) } } @@ -122,3 +124,16 @@ function apply(json) { console.log(text) } } + +function snippet(i, code) { + let pre = args.slice(0, i).join(' ') + let post = args.slice(i + 1).join(' ') + if (pre.length > 20) { + pre = '...' + pre.substring(pre.length - 20) + } + if (post.length > 20) { + post = post.substring(0, 20) + '...' + } + const chalk = require('chalk') + return `\n ${pre} ${chalk.red.underline(code)} ${post}\n` +}