dongliang7545 2015-07-22 14:06
浏览 92
已采纳

从Go中的postgres获取错误代码号

I'm simply unable to retrieve the error code number when I get an error in postgres.

In the test of my program I know I'll get the following error " pq: duplicate key value violates unique constraint "associations_pkey"".

Looking in the postgres docs this is most likely an pq error code of 23505.

I need to get that number in my Go program so that I can check on different types of errors and respond to the end user in a helpful way.

However, I can't seem to get hold of the error code in Go, only the error message. My code is as follows:

stmt, _ := DB.Prepare("INSERT INTO table (column_1) VALUES ($1)")

_, err = stmt.Exec("12324354")

if err != nil {
    log.Println("Failed to stmt .Exec while trying to insert new association")
    log.Println(err.Error())
    fmt.Println(err.Code())

} else {
    Render.JSON(w, 200, "New row was created succesfully")
}
  • 写回答

2条回答 默认 最新

  • dongping1012 2015-07-22 14:10
    关注

    You need to type assert the error to the type *pq.Error:

    pqErr := err.(*pq.Error)
    log.Println(pqErr.Code)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址