Skip to content

Commit

Permalink
fix: more friendly messages for non-string
Browse files Browse the repository at this point in the history
  • Loading branch information
Hoishin committed Feb 14, 2018
1 parent 5200fbe commit 58f8c19
Showing 1 changed file with 24 additions and 19 deletions.
43 changes: 24 additions & 19 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,31 @@ function parseJson (txt, reviver, context) {
try {
return JSON.parse(txt, reviver)
} catch (e) {
const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i)
const errIdx = syntaxErr
? +syntaxErr[1]
: e.message.match(/^Unexpected end of JSON.*/i)
? txt.length - 1
: null
if (errIdx != null) {
const start = errIdx <= context
? 0
: errIdx - context
const end = errIdx + context >= txt.length
? txt.length
: errIdx + context
e.message += ` while parsing near '${
start === 0 ? '' : '...'
}${txt.slice(start, end)}${
end === txt.length ? '' : '...'
}'`
if (typeof txt !== 'string') {
const type = typeof txt === 'undefined' ? ' ' : ` the ${typeof txt} `
e.message = `Cannot parse${type}${String(txt)}`
} else {
e.message += ` while parsing '${txt.slice(0, context * 2)}'`
const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i)
const errIdx = syntaxErr
? +syntaxErr[1]
: e.message.match(/^Unexpected end of JSON.*/i)
? txt.length - 1
: null
if (errIdx != null) {
const start = errIdx <= context
? 0
: errIdx - context
const end = errIdx + context >= txt.length
? txt.length
: errIdx + context
e.message += ` while parsing near '${
start === 0 ? '' : '...'
}${txt.slice(start, end)}${
end === txt.length ? '' : '...'
}'`
} else {
e.message += ` while parsing '${txt.slice(0, context * 2)}'`
}
}
throw e
}
Expand Down

0 comments on commit 58f8c19

Please sign in to comment.