Last active
March 11, 2022 03:40
-
-
Save malipetek/2bac5ffd53317ff7e498f01a4160c6e1 to your computer and use it in GitHub Desktop.
JSON parse with error visualization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function JSONparse (content) { | |
try{ | |
return JSON.parse(content); | |
} catch (err) { | |
try { | |
const offset = parseInt(err.message.match(/position\s+(\d+)/)[1], 10); | |
const linesUntilError = content.slice(0, offset + 1).split('\n'); | |
const errorLine = linesUntilError.length; | |
const contentLines = content.split('\n'); | |
const lineOffset = linesUntilError[linesUntilError.length - 1].length - 1; | |
const message = contentLines.slice(0, errorLine).join('\n') + | |
'\n' + new Array(lineOffset).fill(' ').join('') + | |
'👆\n' + contentLines.slice(errorLine).join('\n'); | |
console.log(message); | |
return {}; | |
} catch (_err) { | |
// could not show error just throw original one then | |
throw err; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment