On Fri, Oct 21, 2022 at 08:17:16AM -0700, David Harel wrote:

> Newbie on golang. Using sqlc: https://github.com/kyleconroy/sqlc in the 
> environment created by Karl Keefer: 
> https://github.com/karlkeefer/pngr/actions/workflows/build.yml, thanks Karl.
> My queries use querier which is auto generated by sqlc.
> 
> Sometime I get an error result in my query such as key violation.
> I want to check the error code of such an error.
> 
> as one of the guys suggested I can look into the object using Marshal
> and I noticed that the error contains a very elaborated, like:
> {"Severity":"ERROR","Code":"23505","Message":"duplicate key value violates
> unique constraint \"treatment_pk\"","Detail":"Key (customer_id, patient_ttz,
> therapist_id, appointment_timestamp)=(1, 060525649, 160, 2022-10-20
> 10:30:00) already
> exists.","Hint":"","Position":"","InternalPosition":"",
> "InternalQuery":"","Where":"","Schema":"public",
> "Table":"treatment","Column":"","DataTypeName":"",
> "Constraint":"treatment_pk","File":"nbtinsert.c","Line":"434",
> "Routine":"_bt_check_unique"}

What is "Marshal" you're referring to here?
Is this encoding/json.Marshal called on some value returned by that
"querier generated by sqlc"?

> Trying to get the same result using straight forward approach like:
> fmt.Printf("%+v\n", err) gives me a much simpler object display.
> 
> How can I get the "smart" content of the error object like the "Code" 
> member?

If my guesseneering is correct, you can just access the Code field of that
value you passed through "Marshal" and analyze it using any convenient method
such as an if or switch statement.

>From [1], I gather that "23505" is indeed a standardized error code for
violation of unique key constraints in PostgreSQL, so basically you could do

  const uniqueKeyViolation = "23505"

  switch result.Code {
  case uniqueKeyViolation:
    // Do something sensible
  default:
    log.Println("unexpected failure: ", result.Code)
  }

Still, please notice that all of the above is what's called "psychic
debugging" and might miss the point partially or completely because your
problem statement is not an MCVE [2]. I'm not sure you could sensibly create
one (as it could have required posting swaths of generated code or something
like this) so please don't take it as a blame.

 1. https://www.postgresql.org/docs/current/errcodes-appendix.html
 2. https://stackoverflow.com/help/minimal-reproducible-example

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/20221025162116.eao4slua2xihi2ta%40carbon.

Reply via email to