Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More friendly messages for non-string #1

Merged
merged 4 commits into from
Mar 30, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ function parseJson (txt, reviver, context) {
try {
return JSON.parse(txt, reviver)
} catch (e) {
if (typeof txt !== 'string') {
const isEmptyArray = Array.isArray(txt) && txt.length === 0
const errorMessage = 'Cannot parse ' +
(isEmptyArray ? 'an empty array' : String(txt))
throw new TypeError(errorMessage)
}
const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i)
const errIdx = syntaxErr
? +syntaxErr[1]
Expand Down
67 changes: 67 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,70 @@ test('parses JSON', t => {
t.deepEqual(JSON.parse(data), parseJson(data), 'does the same thing')
t.done()
})

test('throws SyntaxError for unexpected token', t => {
const data = 'foo'
t.throws(
() => parseJson(data),
new SyntaxError('Unexpected token o in JSON at position 1 while parsing near \'foo\'')
)
t.done()
})

test('throws SyntaxError for unexpected end of JSON', t => {
const data = '{"foo: bar}'
t.throws(
() => parseJson(data),
new SyntaxError('Unexpected end of JSON input while parsing near \'{"foo: bar}\'')
)
t.done()
})

test('throws SyntaxError for unexpected number', t => {
const data = '[[1,2],{3,3,3,3,3}]'
t.throws(
() => parseJson(data),
new SyntaxError('Unexpected number in JSON at position 8')
)
t.done()
})

test('SyntaxError with less context (limited start)', t => {
const data = '{"6543210'
t.throws(
() => parseJson(data, null, 3),
new SyntaxError('Unexpected end of JSON input while parsing near \'...3210\''))
t.done()
})

test('SyntaxError with less context (limited end)', t => {
const data = 'abcde'
t.throws(
() => parseJson(data, null, 2),
new SyntaxError('Unexpected token a in JSON at position 0 while parsing near \'ab...\''))
t.done()
})

test('throws TypeError for undefined', t => {
t.throws(
() => parseJson(undefined),
new TypeError('Cannot parse undefined')
)
t.done()
})

test('throws TypeError for non-strings', t => {
t.throws(
() => parseJson(new Map()),
new TypeError('Cannot parse [object Map]')
)
t.done()
})

test('throws TypeError for empty arrays', t => {
t.throws(
() => parseJson([]),
new TypeError('Cannot parse an empty array')
)
t.done()
})