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条)

报告相同问题?

悬赏问题

  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1