Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Dynamic Errors In Go (Specifically database/sql Package)

Using the database/sql package in go for things like sql.Exec will return dynamically generated, unreferenced errors such as

"Error 1062: Duplicate entry '192' for key 'id'"

The problem is that it can also return errors such as

"Error 1146: Table 'tbl' doesn't exist"

From the same call to sql.Exec

How can I tell the difference between these two errors without

  1. String comparison, or
  2. Pattern matching for error code

Or are those idiomatic viable solutions for this problem?

like image 451
BlinkyTop Avatar asked Dec 25 '14 03:12

BlinkyTop


1 Answers

database/sql package does not solve this problem. It's driver specific. For example, for mysql you can use:

if mysqlError, ok := err.(*mysql.MySQLError); ok {
    if mysqlError.Number == 1146 {
        //handling
    }
}

Also, you can find some error constant package, like mysqlerr from VividCortex, and use it:

if mysqlError, ok := err.(*mysql.MySQLError); ok {
    if mysqlError.Number == mysqlerr.ER_NO_SUCH_TABLE {
        //handling
    }
}

It's not much better than pattern matching, but seems to be more idiomatic.

like image 197
vladwd Avatar answered Sep 20 '22 23:09

vladwd