Skip to content

Commit

Permalink
fix: Ensure error location by custom parsing
Browse files Browse the repository at this point in the history
The native JSON.parse does not always provide the error location
at the end of the error message. These two invalid inputs either
include or not include the error location and it is different
with Node.js 18 and Node.js 20:

  { "foo": \"baz }
  { "foo": baz }

If the locatoin is missing, let us parse the input once more
by the custom parser, which always provides the error location.
  • Loading branch information
prantlf committed Apr 27, 2023
1 parent 30f611a commit 9757213
Showing 1 changed file with 5 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/native-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,10 @@ function parseNative (input, reviver) {
try {
return JSON.parse(input, reviver)
} catch (error) {
throw improveNativeError(input, error)
const newError = improveNativeError(input, error)
if (error.location) throw newError
// If the native error didn't contain location, parse once more
// by the custom parser, which always provides the error location.
return parseCustom (input, reviver)
}
}

0 comments on commit 9757213

Please sign in to comment.