2

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

3 Answers 3

2

I know it's old question, but I just found the solution do not use

 var pgErr *pgconn.PgError

try to use

var pgErr pgx.PgError

instead

Sign up to request clarification or add additional context in comments.

Comments

1

Use pgx.ErrNoRows

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

Comments

1

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.