georgysavva / scany

Library for scanning data from a database into Go structs and more
MIT License
1.23k stars 67 forks source link

Error handling #100

Closed 0radek closed 1 year ago

0radek commented 1 year ago

I'm using pgx v5 and scany v2. Apologies in advance since I'm just a casual Go user and may have missed something obvious.

I've got the following code to insert (with a RETURNING *):

rows, err := s.db.Query(context.Background(), stmt, ...args)
if err != nil {
    return nil, err
}

if err := pgxscan.ScanOne(entity, rows); err != nil {
        /*
        // https://github.com/jackc/pgx/wiki/Error-Handling - how can I make use of this?
    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 nil, err
}

There's a unique constraint, so if I try to insert the same record twice I'll receive the following:

scany: rows final error: ERROR: duplicate key value violates unique constraint ...

How can I get the error code + other details? Thanks

0radek commented 1 year ago

Oof, I realize my mistake now. I am not importing the correct package!

Instead of importing:

"github.com/jackc/pgconn"

I need to import:

"github.com/jackc/pgx/v5/pgconn"