如何提取MongoError:E11000重复密钥的错误消息? [英] How do you extract the error message for MongoError: E11000 duplicate key found?

查看:67
本文介绍了如何提取MongoError:E11000重复密钥的错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为找到的 MongoError:E11000 重复密钥提取错误消息.我只希望错误本身消息而不是整个对象.

How do you extract the error message for MongoError: E11000 duplicate key found. I want just the error itself message not the entire object.

推荐答案

我将在 mongo shell中举例说明:

I will explain this with an example, in mongo shell:

db.test.insertOne( { _id: 1 } )    // insert a document

try { 
    db.test.insertOne( { _id: 1 } ) // insert another document
} 
catch(err) { 
    print(err.code)
    print(err.errmsg)
}

这将显示错误代码值和消息:

This prints the error code value and the message:

E11000
E11000 duplicate key error collection: test.err index: _id_ dup key: { _id: 1.0 }

在终端上看到的实际错误(如果您没有在 try-catch 块中捕获该错误)是这样的:

The actual error as seen on the terminal (if you don't catch it in a try-catch block) is something like this:

WriteError({
        "index" : 0,
        "code" : 11000,
        "errmsg" : "E11000 duplicate key error collection: test.err index: _id_ dup key: { _id: 1.0 }",
        "op" : {
                "_id" : 1
        }
})

WriteResult.writeError 是对象 WriteResult.writeError.code 具有您要查找的错误代码值. WriteResult.writeError.errmsg 包含错误消息.

WriteResult.writeError.code has the error code value you are looking for. WriteResult.writeError.errmsg has the error message.

您可以从任何编程语言应用程序(例如Java,Python,JavaScript/NodeJS等)中类似地获取错误代码和消息值.

You can get the error code and message values similarly from any of the programming language applications (like Java, Python, JavaScript / NodeJS, etc.).

这篇关于如何提取MongoError:E11000重复密钥的错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆