Best way to handling MySQL 1045 Error in Golang

339 views Asked by At

I have a code that control MYSQL Error 1045,

res, err := stmt.Exec(Status, Message, Number)
if err != nil {
    if err.(*mysql.MySQLError).Number == 1045 {
        log.Error(err)
        stmt.Close()
        DatabaseErrorHandling() // used for reCONNECT database
        return false
    } else {
        log.Error(err)
        return true
    }
}

But Error happened like that

panic: interface conversion: error is *errors.errorString, not *mysql.MySQLError

Is there code working like that ?

Any way to handle this error ?

1

There are 1 answers

0
Burak Serdar On

This is failing because the error is not of the type you expect. Use errors.As to verify and convert the error:

var dbErr *mysql.MySQLError
if errors.As(err,&dbErr) {
  // Handle dbErr here
} else {
  // Not a dbErr. Deal with err here.
}