how can i distinguish connection error with other errors when using go-sql-driver -


func mainloop(db *sql.db) {         type pushtask struct {             taskid string             uri    string         }          stmt, err := db.prepare("insert errpushcache(taskid, uri) values(?, ?)")         if err != nil {             log.fatal("db.prepare failed ", err)         }          var (             mysqlok bool = true             task    pushtask         )         {             task.taskid = randstringrunes(8)             task.uri = randstringrunes(16)              res, err := stmt.exec(task.taskid, task.uri)             if err != nil {                 if err == driver.errbadconn {                     if mysqlok {                         log.print("connection mysql seems down, %s", err.error())                         mysqlok = false                         os.exit(1)                     }                 } else {                     log.print("exec failed ", err)                 }                  time.sleep(2 * time.second)                 continue             }             if !mysqlok {                 log.print("connection mysql ok now")                 mysqlok = true             }             lastid, err := res.lastinsertid()             if err != nil {                 log.print("lastinsertid failed ", err)             }             rowcnt, err := res.rowsaffected()             if err != nil {                 log.print("rowsaffected failed ", err)             }             log.printf("id = %d, affected = %d\n", lastid, rowcnt)              time.sleep(20 * time.second)         }     }      func main() {         db, err := sql.open("mysql",             "rench:ren123@tcp(192.168.1.61:3306)/hunantv")         if err != nil {             log.fatal("sql.open failed ", err)         }          mainloop(db)          defer db.close()     } 

in mainloop function, if connection between mysql , client broken,stmt.exec failed, return error, how can distinguish connection error other errors.(err == driver.errbadconn false).

if connection broken, log :

2016/01/29 17:21:31 exec failed dial tcp 192.168.1.61:3306: getsockopt: connection refused 2016/01/29 17:21:33 exec failed dial tcp 192.168.1.61:3306: getsockopt: connection refused 2016/01/29 17:21:35 exec failed dial tcp 192.168.1.61:3306: getsockopt: connection refused 2016/01/29 17:21:37 exec failed dial tcp 192.168.1.61:3306: getsockopt: connection refused 2016/01/29 17:21:39 exec failed dial tcp 192.168.1.61:3306: getsockopt: connection refused

...

network errors of type satisfies net.error interface.

if err, ok := err.(net.error); ok {     log.println("network error:", err) } else {     log.println("other error:", err) } 

in cases won't matter, because action failed some reason, , need handle regardless. it's if want take different action based on network error need check.


Comments