Parsing errors returned by *pgxpool.Pool.QueryRow
into *pgconn.PgError
#1325
-
Firstly - thank you for creating and maintaining this library. For the past month, I've been using pgx v4 (now v5) for a new project and have enjoyed using the library. I'm looking to catch a Postgres table constraint error in order to return a custom error message to the end user. The recommended approach in the Wiki is to use err = conn.QueryRow(context.Background(), "select 1 +").Scan(&greeting)
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
}
} I'm using An abbreviated version of my code is: package main
import (
"github.com/jackc/pgconn"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// Method that is executed
func CreateLog(
... // Variable declarations
env Env,
) (string, error) {
var logID string
err := env.Pool.QueryRow(
context.Background(),
`
SELECT app.create_log(
_user_id := $1::INT,
_source_id := $2::UUID,
_start_date := $3::TIMESTAMP WITH TIME ZONE,
_end_date := $4::TIMESTAMP WITH TIME ZONE,
_start_page := $5::INT,
_end_page := $6::INT,
_title := $7::VARCHAR,
_content := $8::TEXT
);
`,
...
).Scan(&logID)
fmt.Println(err) // Correctly prints - ERROR: new row for relation "log" violates check constraint "page_constraint" (SQLSTATE 23514)
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
fmt.Println(pgErr.Message)
fmt.Println(pgErr.Code)
}
return logID, err
} I don't know if this is a red herring, but using a type assertion ( As I'm receiving the correct error in |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Ah, after digging into the If anyone else makes this mistake with v5, you can just import |
Beta Was this translation helpful? Give feedback.
Ah, after digging into the
pgx
v5 code more I see thatpgconn
was made part ofpgx
now. This is also clearly referenced in theCHANGELOG
and thepgconn
repository.If anyone else makes this mistake with v5, you can just import
github.com/jackc/pgx/v5/pgconn
instead of importinggithub.com/jackc/pgx/pgconn
. The code example in the Wiki works just fine.