1

rows, err:= b.DB.ExecContext(
            ctx,
            fmt.Sprintf(`   
                            UPDATE service_slots
                            SET slots_left  = slots_left - %d
                            WHERE   date = $1 AND 
                                    start_hour = $2 AND
                                    service_id =$3
                        `, serviceSlots.Qty),
            booking.Date,
            booking.Appointment,
            serviceSlots.ID,
        )
        if err!= nil {
            var pgErr *pgconn.PgError
            if errors.As(err, &pgErr) {
                fmt.Println(pgErr.Message) // => syntax error at end of input
                fmt.Println(pgErr.Code)    // => 42601
            }

            return err
        }

tried to use error assert from pgconn, but somehow cannot make the error get inside errors.As(err,&pgErr) if I hit the constraint error or any error from postgres, it just pass the errors.As (did not trigger the printline ) and return the normal error.

what is wrong with my code ?

used

    github.com/jackc/pgx v3.6.2+incompatible
    github.com/jackc/pgconn v1.13.0 // indirect

the error is

"ERROR: new row for relation \"service_slots\" violates check constraint \"slot_nonnegative\" (SQLSTATE 23514)"

-----------SOLVED---------- should not use *pgconn.PgError but should use pgx.PgError instead

thanks to @Adrian for pointing out that I assume the type wrong

  • Then it's not a `pgconn.PgError`. Why do you assume it is that type? – Adrian Sep 29 '22 at 13:50
  • @Adrian the pgx docs from here https://github.com/jackc/pgx/wiki/Error-Handling shows how we can handle error with pgx, so I assume to do the same. if it is not pgconn.PgError is there any way I can search for what kind of error type it is ? – theodorus arie sugiharto Sep 29 '22 at 14:00

0 Answers0