防止bson.ObjectIdHex中的运行时出现紧急情况

问题描述:

我正在尝试使用mgo将objectid字符串转换为bson ObjectId格式,

i'm trying to convert string of objectid to bson ObjectId format with mgo,

errCheck:= dC( col)。 FindId(bson.ObjectIdHex(obid [0]))。One(& Result)

idk为什么,但是如果我输入了错误/无效的输入字符串,我的应用程序出现运行时紧急情况

idk why, but if i give a wrong / invalid input string, my application got runtime panic

我如何防止这种情况发生?谢谢

how i can prevent that ? thank you

bson.ObjectIdHex() 记录说,如果传递无效的对象ID将会恐慌:

bson.ObjectIdHex() documents that it will panic if you pass an invalid object id:


ObjectIdHex从提供的十六进制表示形式返回ObjectId。 使用无效的十六进制表示形式调用此函数会导致运行时出现紧急情况。请参见IsObjectIdHex函数。

ObjectIdHex returns an ObjectId from the provided hex representation. Calling this function with an invalid hex representation will cause a runtime panic. See the IsObjectIdHex function.

如果您想要避免这种情况,请首先使用 检查您的输入字符串bson.IsObjectIdHex() ,并且只有输入有效时才继续调用 bson.ObjectIdHex()

If you want to avoid this, first check your input string using bson.IsObjectIdHex(), and only proceed to call bson.ObjectIdHex() if your input is valid:

if bson.IsObjectIdHex(obid[0]) {
    // It's valid, calling bson.ObjectIdHex() will not panic...
}