如何在Golang中使用pgx驱动程序处理PostgreSQL查询错误?

huangapple go评论95阅读模式
英文:

How to handle postgres query error with pgx driver in golang?

问题

我阅读了这个关于错误处理的官方指南,并进行了应用。

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
    }
}

代码没有起作用,我的应用程序没有打印任何内容。但是Postgres日志中有ERROR: duplicate key value violates unique constraint "articles_uri_key"

好的,我可以使用标准的Golang方法:

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

有一个问题,当Postgres日志中没有错误时,它会打印no rows in result set

我尝试将if err != nil替换为if err != errors.New("no rows in result set"),但它仍然打印no rows in result set

英文:

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

答案1

得分: 1

使用pgx.ErrNoRows

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

Use pgx.ErrNoRows

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

答案2

得分: 1

请修改你的问题,使其合适。

重复键值是一个有效的错误。如果你想要移除这个错误,你可以避免重复的条目,或者移除它的唯一约束。

在使用pgx和database/sql时,pgx只是作为驱动程序。sql.ErrNoRows错误是从database/sql库返回的。只有在直接调用pgx函数时才会返回pgx.ErrNoRows。因为database/sql会从驱动程序中传递一些错误。

sqlStatement := `
   INSERT INTO articles (uri)
    VALUES ($1)
    RETURNING id`
    id := 0
   //确保你想要扫描的数据类型应该传递到scan()函数中
    err = db.QueryRow(sqlStatement, article.URI).Scan(&id)
    if err != nil {
	if err == sql.ErrNoRows {   //pgx.ErrNoRows
		//没有行,但没有发生其他错误
	} else {
		log.Fatal(err)
	}
}
    fmt.Println("New record ID is:", id)

为了更好地理解或处理多行,请参考此链接:https://stackoverflow.com/questions/70208076/how-to-get-row-values-back-after-db-insert/70209795#70209795

英文:

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 : https://stackoverflow.com/questions/70208076/how-to-get-row-values-back-after-db-insert/70209795#70209795

答案3

得分: 0

我知道这是一个旧问题,但我刚刚找到了解决方案。不要使用var pgErr *pgconn.PgError,而是尝试使用var pgErr pgx.PgError

英文:

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

huangapple
  • 本文由 发表于 2021年12月29日 14:09:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/70515729.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定