刚开始使用Go,目前正在尝试创建REST API。使用gorm
和gin
做同样的事情。卡住的地方是,我试图从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
它进入地图然后最终使用它。
有更简单的方法吗?
断言它到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
}