Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the error type from 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.

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?

like image 702
Sir Avatar asked Oct 30 '17 06:10

Sir


2 Answers

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 separately 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

like image 91
Philidor Avatar answered Nov 19 '22 09:11

Philidor


normally in packages you could see Variables if the package author want to separate errors make variable for each of them like : https://golang.org/pkg/database/sql/#pkg-variables

you could see errors and you could switch the error in return and case each error variable.

example:

result, err := db.Exec("INSERT INTO users (username,password,email) VALUES (?,?,?)", username, hashedPassword, email)
if err == sql.ErrNoRows {
    // handle error
    return
}
if err == sql.ErrTxDone {
    // handle error
    return
}
like image 43
Jeyem Avatar answered Nov 19 '22 08:11

Jeyem