Reputation: 21
When working with the sqlite database in Go. During the testing I got the error: no such table: table_name
.
Well I know where the error is coming from.
But I want to know if there is a way that I can use this error message in Go, to do some work with it(like create that table in my code). I was trying to do something like this:
_, err := getState(dbconn) // This the function that retrieves the table that does not exists
if err != nil {
if err == err.New("no such table: table_name") {
// do the work
}
}
Upvotes: 0
Views: 64
Reputation: 9034
As mentioned elsewhere, you cannot compare the value returned by errors.New()
to err
using ==
operator as it'd compare for equality in reference and not the actual error type.
Instead, you can try either of the following approaches.
// compare the err's string value for exact match
if err != nil {
if strings.EqualFold(err.Error(), "no such table: table_name") {
// handle not found error
}
}
type NotFound struct{}
func (nf *NotFound) Error() string {
return errors.New("no such table")
}
func (nf *NotFound) Is(err error) bool {
return err != nil && strings.HasPrefix(err.Error(), "no such table")
}
var ErrNotFound = &NotFound{}
// ...somewhere in your code
_, err := getState(dbConn)
if err != nil {
// compare using errors.Is()
if errors.Is(err, ErrNotFound) {
// handle not found error
}
}
Upvotes: 0
Reputation: 180
In Go, errors returned by SQLite, such as "no such table," cannot be compared to a string using err.New("no such table: table_name"). This is because the "no such table" error is returned as an sqlite3.Error object, not as a string.
To handle this error, you should check the error message using the Error() method:
_, err = getState(dbconn)
if err != nil {
if err.Error() == "no such table: table_name" {
fmt.Println("Creating the table")
// do the work
}
}
Upvotes: -2