Prevent runtime panic in bson.ObjectIdHex

前端 未结 2 1916
囚心锁ツ
囚心锁ツ 2021-01-23 09:47

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

errCheck := d.C(\"col\").FindId(bson.ObjectIdHex(obid[0])).One(&Result)

2条回答
  •  不要未来只要你来
    2021-01-23 10:29

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

    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.

    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...
    }
    

提交回复
热议问题