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

如何在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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵