doucong1992 2017-10-30 06:15
浏览 1019
已采纳

如何在golang中获取mySQL错误类型?

I'm really confused how to get the error type from a failed query line with the mySQL import. There is no real documentation on it, so it has me real confused.

Currently i have:

result, err := db.Exec("INSERT INTO users (username,password,email) VALUES (?,?,?)", username, hashedPassword, email)
if err != nil {
    // handle different types of errors here
    return
}

I could print err but its just a string, not liking the idea of peeking at strings to know what went wrong, is there no feedback to get an error code to perform a switch on or something along those lines? How do you do it?

  • 写回答

2条回答 默认 最新

  • douzhuijing4911 2017-10-30 06:46
    关注

    Indeed, checking the content of the error string is a bad practice, the string value might vary depending on the driver verison. It’s much better and robust to compare error numbers to identify what a specific error is.

    There are the error codes for the mysql driver, the package is maintained separatly from the main driver package. The mechanism to do this varies between drivers, however, because this isn’t part of database/sql itself. With that package you can check the type of error MySQLError:

    if driverErr, ok := err.(*mysql.MySQLError); ok {
        if driverErr.Number == mysqlerr.ER_ACCESS_DENIED_ERROR {
            // Handle the permission-denied error
        }
    }
    

    There are also error variables.

    Ref

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么