Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse MySQL errors

I am trying to parse MySQL errors in order to return clean error messages to the user from a Go 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 doesn't support parseError.

To give a concrete example, 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 languages and send ready-to-use error messages back to the client.

Thank you!

like image 974
Adrien Avatar asked Jul 21 '16 02:07

Adrien


1 Answers

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

like image 87
Meehow Avatar answered Sep 19 '22 19:09

Meehow