将错误转换为map或struct

问题描述 投票:0回答:1

刚开始使用Go,目前正在尝试创建REST API。使用gormgin做同样的事情。卡住的地方是,我试图从error对象中获取一个值,但是我无法以直接的方式做到这一点。

error类型,如果我知道的话,只有一个Error方法可用,它给出了对象的Message部分中的任何内容。这是我的错误对象。

{
    "Severity": "ERROR",
    "Code": "23505",
    "Message": "duplicate key value violates unique constraint \"uix_users_email\"",
    "Detail": "Key (email)=([email protected]) already exists.",
    "Hint": "",
    "Position": "",
    "InternalPosition": "",
    "InternalQuery": "",
    "Where": "",
    "Schema": "public",
    "Table": "users",
    "Column": "",
    "DataTypeName": "",
    "Constraint": "uix_users_email",
    "File": "nbtinsert.c",
    "Line": "433",
    "Routine": "_bt_check_unique"
}

现在,我想要做的是,访问Detail密钥,我有点困惑。这是我目前为实现这一目标所做的工作:

if err := a.DB.Create(&user).Error; err != nil {
    val, _ := json.Marshal(err)
    m := make(map[string]string)
    json.Unmarshal(val, &m)
    context.JSON(422, gin.H{"error": m["Detail"]})
    return
}

但这似乎有点矫枉过正。我必须Marshal错误,然后Unmarshal它进入地图然后最终使用它。

有更简单的方法吗?

go go-gorm
1个回答
1
投票

断言它到pq.Error并访问字段as explained in the pq docs

if err, ok := err.(*pq.Error); ok {
    fmt.Println("pq error:", err.Code.Name())
    // Or whatever other field(s) you need
}

full type is also documented

© www.soinside.com 2019 - 2024. All rights reserved.