Search code examples
mongodbgobsonmgo

Prevent runtime panic in bson.ObjectIdHex


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)

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

how i can prevent that ? thank you


Solution

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