登录
首页 >  Golang >  Go问答

避免在 bson.ObjectIdHex 中发生运行时恐慌

来源:stackoverflow

时间:2024-03-08 22:00:29 270浏览 收藏

哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《避免在 bson.ObjectIdHex 中发生运行时恐慌》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!

问题内容

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

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

我不知道为什么,但如果我给出错误/无效的输入字符串,我的应用程序就会出现运行时恐慌

我怎样才能防止这种情况发生?谢谢


解决方案


bson.ObjectIdHex() 文档表明,如果您传递无效的对象 id,它将出现紧急情况:

objectidhex 从提供的十六进制表示中返回一个 objectid。 使用无效的十六进制表示调用此函数将导致运行时恐慌。请参阅 isobjectidhex 函数。

如果您想避免这种情况,请首先使用 bson.IsObjectIdHex() 检查您的输入字符串,然后仅在您的输入有效时才继续调用 bson.objectidhex()

if bson.isobjectidhex(obid[0]) {
    // it's valid, calling bson.objectidhex() will not panic...
}

正如@icza在上一个答案中所说。您应该检查 objectid 的有效性。 并且您可以使用 panic recover defer 来处理将来的任何类型的错误

package main

import (
    "fmt"
    "gopkg.in/mgo.v2/bson"
    "path/filepath"
    "runtime"
    "strings"
)

func main() {
    r := Result{}
    getData(&r)
}

func IdentifyPanic() string {
    var name, file string
    var line int
    var pc [16]uintptr

    n := runtime.Callers(3, pc[:])
    for _, pc := range pc[:n] {
        fn := runtime.FuncForPC(pc)
        if fn == nil {
            continue
        }
        file, line = fn.FileLine(pc)
        name = fn.Name()

        if !strings.HasPrefix(name, "runtime.") {
            break
        }
    }
    file = filepath.Base(file)

    switch {
    case name != "":
        return fmt.Sprintf("%v:%v", file, line)
    case file != "":
        return fmt.Sprintf("%v:%v", file, line)
    }

    return fmt.Sprintf("pc:%x", pc)
}

type Result struct {
    success int
    data string
}
func getData(result *Result){
    defer func() {
        if err := recover(); err != nil {
            ip := IdentifyPanic()
            errorMessage := fmt.Sprintf("%s Error: %s", ip, err)
            fmt.Println(errorMessage)
            result.success = 0
        }
    }()
    if bson.IsObjectIdHex(obid[0]) {                                 // this line copied from @icza answer
        // It's valid, calling bson.ObjectIdHex() will not panic...  // this line copied from @icza answer
        errCheck := d.C("col").FindId(bson.ObjectIdHex(obid[0])).One(&res)
        result.success = 1
        result.data = "your result (res). this is just the exam"
    }else{
        result.success = 0  
    }
}

到这里,我们也就讲完了《避免在 bson.ObjectIdHex 中发生运行时恐慌》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>