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

时间:2022-11-29 14:40:38

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 }

{[错误:ER_DUP_ENTRY:重复条目'sample@gmail.com'代表密钥'email']代码:'ER_DUP_ENTRY',错误号:1062,sqlState:'23000',索引:0}

What I want to do is turn this Error object into a string. I tried using JSON.stringify() and when I printed it on the console, only the last part got converted into a string :

我想要做的是将此Error对象转换为字符串。我尝试使用JSON.stringify(),当我在控制台上打印它时,只有最后一部分被转换为字符串:

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

{ “代码”: “ER_DUP_ENTRY”, “错误号”:1062, “SQLSTATE”: “23000”, “索引”: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对象转换为字符串时,如何检索该部分?

2 个解决方案

#1


11  

I thought I had to use JSON for this problem because of the way the Error object was formatted. How I solved this one was just to use

我认为由于Error对象的格式化方式,我必须使用JSON来解决这个问题。我如何解决这个问题只是为了使用

err.toString()

#2


1  

For future reference, just in case you wish to extract the Error messsage. Use error.message to extract the message. Here is a reference: https://nodejs.org/api/errors.html#errors_error_message

供将来参考,以防您希望提取错误消息。使用error.message提取消息。这是一个参考:https://nodejs.org/api/errors.html#errors_error_message

#1


11  

I thought I had to use JSON for this problem because of the way the Error object was formatted. How I solved this one was just to use

我认为由于Error对象的格式化方式,我必须使用JSON来解决这个问题。我如何解决这个问题只是为了使用

err.toString()

#2


1  

For future reference, just in case you wish to extract the Error messsage. Use error.message to extract the message. Here is a reference: https://nodejs.org/api/errors.html#errors_error_message

供将来参考,以防您希望提取错误消息。使用error.message提取消息。这是一个参考:https://nodejs.org/api/errors.html#errors_error_message