drze7794 2014-12-25 03:31
浏览 103
已采纳

在Go中处理动态错误(特别是数据库/ sql程序包)

Using the database/sql package in go for things like sql.Exec will return dynamically generated, unreferenced errors such as

"Error 1062: Duplicate entry '192' for key 'id'"

The problem is that it can also return errors such as

"Error 1146: Table 'tbl' doesn't exist"

From the same call to sql.Exec

How can I tell the difference between these two errors without

  1. String comparison, or
  2. Pattern matching for error code

Or are those idiomatic viable solutions for this problem?

  • 写回答

2条回答 默认 最新

  • duanguan5922 2014-12-26 19:48
    关注

    database/sql package does not solve this problem. It's driver specific. For example, for mysql you can use:

    if mysqlError, ok := err.(*mysql.MySQLError); ok {
        if mysqlError.Number == 1146 {
            //handling
        }
    }
    

    Also, you can find some error constant package, like mysqlerr from VividCortex, and use it:

    if mysqlError, ok := err.(*mysql.MySQLError); ok {
        if mysqlError.Number == mysqlerr.ER_NO_SUCH_TABLE {
            //handling
        }
    }
    

    It's not much better than pattern matching, but seems to be more idiomatic.

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

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多