-2
 console.log(JSON.parse(buffer.toString())) 

This is output the error

      else throw err
           ^

SyntaxError: Unexpected token a in JSON at position 0
    at JSON.parse (<anonymous>)
    at Object.handler (C:\Users\catprogrammer\Desktop\node.js\notes-app\app.js:36:26)
    at Object.runCommand (C:\Users\catprogrammer\Desktop\node.js\notes-app\node_modules\yargs\lib\command.js:240:40)
    at Object.parseArgs [as _parseArgs] (C:\Users\catprogrammer\Desktop\node.js\notes-app\node_modules\yargs\yargs.js:1107:41)
    at Object.parse (C:\Users\catprogrammer\Desktop\node.js\notes-app\node_modules\yargs\yargs.js:566:25)
    at Object.<anonymous> (C:\Users\catprogrammer\Desktop\node.js\notes-app\app.js:85:7)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14) 

how can I rule out a error of JSON. For example use if(){} condition to check error. I need that the program will not stop with this error. How I can do it? I wanna something this:

if(JSON.parse('hello there!'){
    console.log('This is impossible!!')
}else{
    console.log('Parsing to object...')
}

1 Answers1

0

In JS, thrown runtime errors can be caught using a try/catch structure:

try{
  //Maybe erroneous code here
}catch(error){
  //Handle the error
}

When an exception is thrown inside the try{} block, the try block's execution is halted, and the catch part gets the error as 'argument', and runs.

If no error happened inside try, the catch block doesn't run.

Note: exceptions thrown from the catch block aren't caught.

So, convert your code to something like:

try{
  let object = JSON.parse(buffer.toString())
  console.log('Parsed to object: ', object)
}catch(e){
  console.log("That's impossible because: ", e)
}

If you don't actually have to parse the string, just check whether is it parseable or not, it could be faster, or more memory effecient to pass a reviver function, that always returns undefined.

That way, you allow all parsed objects to be garbage collected, if needed:

try{
  JSON.parse(buffer.toString(), /* this will return undefined: */ ()=>{})
  console.log('Parseable')
}catch(e){
  console.log("That's impossible because:", e)
}
FZs
  • 16,581
  • 13
  • 41
  • 50