Just started with Go and currently trying to create a REST API. Using gorm
& gin
to do the same. Where am stuck is, am trying to fetch a value from the error
object, but am not able to do that in a straight forward way.
The error
type, if I know correctly, just hasa an Error
method available, which gives whatever is in the Message
part of the object. This is the error object I have.
{
"Severity": "ERROR",
"Code": "23505",
"Message": "duplicate key value violates unique constraint \"uix_users_email\"",
"Detail": "Key (email)=(johndoe@gmail.com) 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"
}
Now, what I want to do is, access the Detail
key, and am a bit confused. This is what I have currently done to be able to achieve this:
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
}
But this seems like an overkill. I have to Marshal
the error, then Unmarshal
it into a map & then finally use it.
Is there a simpler way to do this?
Assert it to pq.Error
and access the fields 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
}