Home Access Unique Constraint error in lib/pq
Reply: 0

Access Unique Constraint error in lib/pq

driftavalii
1#
driftavalii Published in 2018-01-12 18:46:38Z

I would like to handle a postgresql unique constraint error by accessing the error code. I have gone through these articles here and here and also gone through the documentation here, but still don't quite understand how to implement this and access the errorcode returned by the db. It seems only the Message field method was implemented:

func (err Error) Error() string {
    return "pq: " + err.Message
}

If I want to access the SQLSTATE code, Do I implement something like:

func (err *Error) Error() string {
  return err.Code
}

and assume the Error struct as defined here will be available.

I have tried something in my handler like this:

sqlInsert := INSERT INTO usrtable (usrCode, teamName, email, phone) VALUES ($1,$2,$3,$4)

_, err := db.Exec(sqlInsert, Data.UsrCode, Data.Teamname, Data.Email, Data.Phone)
if err != nil {
        switch err {
        case errorCodeNames["23505"]:
            // Return web page identifying field and advising user what to do.
            return

This returns undefined which makes sense since errorCodeNames is not exported but I am stumped regarding how to achieve this.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.298299 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO