Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a message in error handling with try, catch

I have a simple example:

var str = '{ "test"  : 1, }'  try {     JSON.parse(str); } catch (e) {     console.log(e) } 

result:

[SyntaxError: Unexpected token }]

How to print all error info ?

Expected result:

undefined:1 { "test"  : 1, }          ^ SyntaxError: Unexpected token } 
like image 847
Bdfy Avatar asked Jan 11 '13 10:01

Bdfy


People also ask

How do I print exception details in Python?

If you are going to print the exception, it is better to use print(repr(e)) ; the base Exception. __str__ implementation only returns the exception message, not the type. Or, use the traceback module, which has methods for printing the current exception, formatted, or the full traceback.

How do you catch error messages in Python?

message (at least in Python 2.7. 12). If you want to capture the error message, use str(e) , as in the other answers.

How do I print exception messages in Python 3?

Python3. Method 2: By using print_exception() method. This method prints exception information and stack trace entries from traceback object tb to file.


2 Answers

This will help:

var x = { asd: "asd", };  try {     JSON.parse(x); } catch (e) {     console.log("Error", e.stack);     console.log("Error", e.name);     console.log("Error", e.message); } 

error.stack is not exactly what you want, but it will help you.

like image 52
randunel Avatar answered Sep 23 '22 01:09

randunel


This will show you the various ways in which you can get the info available:

var str = '{"test": 1, }';  try {     JSON.parse(str); } catch(e) {      console.log("error object:");     console.log(e);     console.log();      console.log("error object toString():");     console.log("\t" + e.toString());      console.log();     console.log("error object attributes: ");     console.log('\tname: ' + e.name + ' message: ' + e.message + ' at: ' + e.at + ' text: ' + e.text);      console.log();     console.log("error object stack: ");     console.log(e.stack); } 

The output is:

error object: [SyntaxError: Unexpected token }]  error object toString():     SyntaxError: Unexpected token }  error object attributes:      name: SyntaxError message: Unexpected token } at: undefined text: undefined  error object stack:  SyntaxError: Unexpected token }     at Object.parse (native)     at Object.<anonymous> (/home/james/devel/tests/node/test.js:4:10)     at Module._compile (module.js:449:26)     at Object.Module._extensions..js (module.js:467:10)     at Module.load (module.js:356:32)     at Function.Module._load (module.js:312:12)     at Module.runMain (module.js:492:10)     at process.startup.processNextTick.process._tickCallback (node.js:244:9) 

You can take your pick :-)

like image 30
Metalskin Avatar answered Sep 25 '22 01:09

Metalskin