How to parse mysql error golang

I am trying to parse mySQL errors in order to return a clean error message to the user from my golang API. I read some article, for example this one , which shows what I would like to do, but it looks like the go-mysql-driver module that I use does not support parseError.

To give a concrete example of what I'm trying to achieve, with an error:

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

I would like to be able to create a data structure that allows me to organize information in order to return a user-friendly message, for example

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

therefore, I can also translate it into another language and directly print it on the client side.

Thank!

+4
source share
2 answers

I found some tips 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 me.Numbercan be found in mysql documentation

+10
source

This error occurs directly from the server, to a large extent you will have to analyze the error string ( err.Error()) yourself .

-2
source

Source: https://habr.com/ru/post/1648597/


All Articles