简体   繁体   English

如何正确地将节点js中的Error对象转换为字符串?

[英]How do I convert an Error object in node js to a string properly?

This error throws up whenever I enter a duplicate entry in mysql. 每当我在mysql中输入重复条目时,都会抛出此错误。

{ [Error: ER_DUP_ENTRY: Duplicate entry 'sample@gmail.com' for key 'email '] code: 'ER_DUP_ENTRY', errno: 1062, sqlState: '23000', index: 0 }

What I want to do is turn this Error object into a string. 我想要做的是将此Error对象转换为字符串。 I tried using JSON.stringify() and when I printed it on the console, only the last part got converted into a string : 我尝试使用JSON.stringify(),当我在控制台上打印它时,只有最后一部分被转换为字符串:

{"code":"ER_DUP_ENTRY","errno":1062,"sqlState":"23000","index":0}

I need to convert the first part as well of the error, the one inside the [ ] so that I am able to diagnose duplicates properly. 我需要转换第一部分以及错误,即[]中的一部分,以便我能够正确诊断重复项。 How do I retrieve that part whenever I convert an Error object into a string? 每当我将Error对象转换为字符串时,如何检索该部分?

I thought I had to use JSON for this problem because of the way the Error object was formatted. 由于Error对象的格式化方式,我认为我必须使用JSON来解决这个问题。 How I solved this one was just to use 我如何解决这个问题只是为了使用

err.toString()

For future reference, just in case you wish to extract the Error messsage. 供将来参考,以防您希望提取错误消息。 Use error.message to extract the message. 使用error.message提取消息。 Here is a reference: https://nodejs.org/api/errors.html#errors_error_message 这是一个参考: https//nodejs.org/api/errors.html#errors_error_message

To get the full stack use stack property of the Error object: 要获取完整堆栈,请使用Error对象的stack属性:

console.log(error.stack)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM