Home > Software engineering >  How to handle postgres query error with pgx driver in golang?
How to handle postgres query error with pgx driver in golang?

Time:12-30

I read this official guide about error handling

i applied it

err := db.connection.QueryRow("INSERT INTO articles(uri) VALUES ($1)", article.URI).Scan()
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
    }
}

Code doesn't work, my app doens't print anything. But postgres log has ERROR: duplicate key value violates unique constraint "articles_uri_key"

Ok, i can use standart golang method:

err := db.connection.QueryRow("INSERT INTO articles(uri) VALUES ($1)", article.URI).Scan()
if err != nil {
    fmt.Println(err)
}

One problem, it prints no rows in result set when no errors in postgres log.

I tried replace if err != nil with if err != errors.New("no rows in result set"),

it still prints no rows in result set

CodePudding user response:

Use pgx.ErrNoRows

if err != pgx.ErrNoRows {
    fmt.Println(err)
}

CodePudding user response:

Please modify your question and make it appropriate.

Duplicate key value is a valid error. If you want to remove the error either you should avoid duplicate entry or remove unique constraint from it.

Using pgx with database/sql, pgx is simply acting as driver.The sql.ErrNoRows error is being returned from the database/sql library. pgx.ErrNoRows is only returned when calling a pgx function directly. As database/sql will bubble up some errors from the driver.

sqlStatement := `
   INSERT INTO articles (uri)
    VALUES ($1)
    RETURNING id`
    id := 0
   //make sure what type of data you want to scan you should pass it inside scan()
    err = db.QueryRow(sqlStatement, article.URI).Scan(&id)
    if err != nil {
    if err == sql.ErrNoRows {   //pgx.ErrNoRows
        // there were no rows, but otherwise no error occurred
    } else {
        log.Fatal(err)
    }
}
    fmt.Println("New record ID is:", id)

For better understanding or for multiple rows please refer this link : How to get row value(s) back after db insert?

  • Related