Skip to content

Commit

Permalink
Switch from jju to json-parse-better-errors for detailed errors (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
bcoe authored and sindresorhus committed Nov 4, 2017
1 parent aacda96 commit f9149d8
Show file tree
Hide file tree
Showing 6 changed files with 14 additions and 849 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
node_modules
yarn.lock
.nyc_output
coverage
27 changes: 5 additions & 22 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,9 @@
'use strict';
const errorEx = require('error-ex');
const fallback = require('./vendor/parse');

function appendPosition(message) {
const posRe = / at (\d+:\d+) in/;
const numbers = posRe.exec(message);
return message.replace(posRe, ' in') + ':' + numbers[1];
}
const fallback = require('json-parse-better-errors');

const JSONError = errorEx('JSONError', {
fileName: errorEx.append('in %s'),
appendPosition: {
message: (shouldAppend, original) => {
if (shouldAppend) {
original[0] = appendPosition(original[0]);
}
return original;
}
}
fileName: errorEx.append('in %s')
});

module.exports = (input, reviver, filename) => {
Expand All @@ -30,19 +16,16 @@ module.exports = (input, reviver, filename) => {
try {
return JSON.parse(input, reviver);
} catch (err) {
fallback.parse(input, {
mode: 'json',
reviver
});
fallback(input, reviver);

throw err;
}
} catch (err) {
const jsonErr = new JSONError(err);
err.message = err.message.replace(/\n/g, '');

const jsonErr = new JSONError(err);
if (filename) {
jsonErr.fileName = filename;
jsonErr.appendPosition = true;
}

throw jsonErr;
Expand Down
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
"node": ">=4"
},
"scripts": {
"test": "xo && ava"
"test": "nyc ava",
"posttest": "xo"
},
"files": [
"index.js",
Expand All @@ -32,10 +33,12 @@
"str"
],
"dependencies": {
"error-ex": "^1.3.1"
"error-ex": "^1.3.1",
"json-parse-better-errors": "^1.0.1"
},
"devDependencies": {
"ava": "*",
"nyc": "^11.2.1",
"xo": "*"
}
}
4 changes: 2 additions & 2 deletions test.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import test from 'ava';
import m from '.';

const reJsonErr = /JSONError: Trailing.*in foo\.json(:\d+:\d+)?/;
const reJsonErr = /JSONError: Unexpected token }.*in foo\.json?/;

test(t => {
t.truthy(m('{"foo": true}'));

t.throws(() => {
m('{\n\t"foo": true,\n}');
}, /JSONError: Trailing/);
}, /JSONError: Unexpected token }/);

t.throws(() => {
try {
Expand Down
Loading

0 comments on commit f9149d8

Please sign in to comment.