javascript 如何使用 try、catch 在错误处理中打印消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14275757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:12:15  来源:igfitidea点击:

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

javascriptnode.js

提问by Bdfy

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 }

回答by randunel

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.stackis not exactly what you want, but it will help you.

error.stack不完全是你想要的,但它会帮助你。

回答by Metalskin

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 :-)

你可以选择:-)