N
N
nano_e_t_42017-09-07 11:37:57
go
nano_e_t_4, 2017-09-07 11:37:57

How to process the error code to the database?

Hi everyone
, I have this code:

insert := fmt.Sprintf("insert into la (bla, data_time, kla) values (%d, now(), \"df\"')", ga)
    _, err := db.Exec(insert)
    if err != nil {
      fmt.Println(err)
    }

There is no kla column in the table, so an error is printed to the console. I need an error code to process it. Reflect says that the error type is *pq.Error. github says that this structure has many fields, including Code, Message.
But when you try to access this field, an error occurs that there are no such fields.
To be honest, I don’t know.
In general, I want to take the error code and process it in the right way. But it is impossible to get the error code, because there is no such field in the structure (

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2017-09-07
@nano_e_t_4

db.Exec returns the error interface, you need to try to cast it to *pq.Error in order to process it.

_, err := db.Exec(insert)
if err != nil {
    if pgError,ok := err.(*pq.Error); ok {
        // Достаём код из переменной pgError
    } else {
        // Пришедший тип не является *pg.Error
    }
}

And the most important thing!
NEVER use Sprintf to form a query, you open SQL Injection in your code. Use the substitution feature provided by the database/sql package
db.Query("select id, name from users where id = ?", 1) // Вот так, например

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question