admin管理员组文章数量:1327268
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
}
}
本文标签: sqliteHow can I handle a quotno such tablequot errorStack Overflow
版权声明:本文标题:sqlite - How can I handle a "no such table" error? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742210068a2433546.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论