With an SQLite database in Go I got:
no such table: table_name
I know where it is coming from but how can I use this error message in Go to create that table, like:
_, 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
}
}
With an SQLite database in Go I got:
no such table: table_name
I know where it is coming from but how can I use this error message in Go to create that table, like:
_, 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
}
}
Share
Improve this question
edited Feb 8 at 3:17
user4157124
3,00214 gold badges31 silver badges46 bronze badges
asked Dec 12, 2024 at 16:51
guts_thakurguts_thakur
195 bronze badges
2
- 2 "Well I know where the error is coming from". In that cas please show the code that causes the error, as it will be more useful. – OldBoy Commented Dec 12, 2024 at 17:04
- From the docs: "Each call to New returns a distinct error value even if the text is identical". Either the package you are using provides a specific error type which can be inspected, or you have to compare against the error string. – Mr_Pink Commented Dec 12, 2024 at 17:12
2 Answers
Reset to default 1You cannot compare the value returned by errors.New()
to err
using the ==
operator as it compares for equality in reference and not the actual error type. Try 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
}
}
Errors returned by SQLite cannot be compared to a string using err.New("no such table: table_name")
because it is an sqlite3.Error
object, not a string.
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
}
}