简体   繁体   中英

Best way to handling MySQL 1045 Error in Golang

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?

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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM