Skip to content

Instantly share code, notes, and snippets.

@wrongbyte
Last active September 22, 2021 12:10
Show Gist options
  • Save wrongbyte/a8463cd0c20b123eba092c50b0ac048e to your computer and use it in GitHub Desktop.
Save wrongbyte/a8463cd0c20b123eba092c50b0ac048e to your computer and use it in GitHub Desktop.
catch errors from JSON.parse (from nodeschool workshop)
// Some invalid JSON will be available on process.argv[2].
// Build a function called `parsePromised` that creates a promise,performs `JSON.parse` in a `try`/`catch` block, and fulfills or rejects the promise depending on whether an error is thrown.**Note:** your function should synchronously return the promise!
// Build a sequence of steps like the ones shown above that catchesany thrown errors and logs them to the console.
JSONdata = process.argv[2]
function parsePromise(data) {
return new Promise(function(fulfill, reject){
try{
parsedData = JSON.parse(data)
fulfill(parsedData)
} catch(error){
reject(error)
}
});
}
// Podemos usar then pq a função retorna uma promise
parsePromise(JSONdata).then(null, function onReject(error) {
console.log(error.message)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment