如何解析mysql错误golang

如何解析mysql错误golang

问题描述:

I am trying to parse mySQL errors in order to return clean error message to the user from my golang API. I read some article like this one that show what I would like to do but it looks like the module go-mysql-driver that I am using don't support parseError.

To give a concrete example of what I try to achieve, with the error:

Error 1062: Duplicate entry 'John' for key 'name_UNIQUE'

I would like to be able to build a data structure that allow me to organize the information in order to return a user friendly message like

Error with the field 'name': 'John' already exist"

so I can also translate it in different language and directly print it client side.

Thank you!

我正在尝试解析mySQL错误,以便从我的golang API向用户返回干净的错误消息。 I 阅读诸如这样的文章,该文章显示了我想做的事情,但是它 我正在使用的模块 go-mysql-driver 不支持parseError。 p>

要给出我尝试实现的具体示例,并出现以下错误: p>

 错误1062:重复输入“ John” 键'name_UNIQUE'
  code>  pre> 
 
 

我希望能够建立一个数据结构,该结构允许我组织信息以返回用户友好的消息,例如 p>

 字段'name'的错误:'John'已经存在“ 
  code>  pre> 
 
 

,所以我也可以将其翻译为 p>

谢谢! p> div>

I found some hints in packets.go and driver_test.go

Example:

me, ok := err.(*mysql.MySQLError)
if !ok {
    return err
}
if me.Number == 1062 {
    return errors.New("It already exists in a database.")
}
return err

Possible values of me.Number can be found in mysql documentation

That error comes directly from the server, pretty much you would have to parse the error string (err.Error()) yourself.