我已经创建了一个“基本”存储库结构,可用于独立和嵌入式使用(例如与CustomerRepository一起使用),以避免不断检查错误,并为Gorp(数据库工具包)创建抽象层,并创建一个更符合我的API。在这个基本结构中,我会检查错误并出现问题时会引发panic,因为在我看来,如果存在一个错误,则表示开发人员错误,代码可能会panic,因为验证等应该在数据到达存储库之前进行。我找到了这个问题Go Error Handling Techniques,但它没有涵盖像我所做的那样将错误封装在基本结构中并仅仅引发panic。我所做的是否符合Go语言惯例?
package repositories
import (
"github.com/coopernurse/gorp"
)
type Repository struct {
Gorp gorp.SqlExecutor
}
func (r *Repository) GetById(i interface{}, id int) interface{} {
obj, err := r.Gorp.Get(i, id)
if err != nil {
panic(err)
}
return obj
}
func (r *Repository) Get(holder interface{}, query string, args ...interface{}) interface{} {
if err := Gorp.SelectOne(holder, query, args); err != nil {
panic(err)
}
}
func (r *Repository) Select(i interface{}, query string, args ...interface{}) {
if _, err := Gorp.Select(holder, query, args); err != nil {
panic(err)
}
}
func (r *Repository) Insert(list ...interface{}) {
if err := r.Gorp.Insert(list...); err != nil {
panic(err)
}
}
func (r *Repository) Update(list ...interface{}) int64 {
count, err := r.Gorp.Update(list...)
if err != nil {
panic(err)
}
return count
}
func (r *Repository) Delete(list ...interface{}) int64 {
count, err := r.Gorp.Delete(list...)
if err != nil {
panic(err)
}
return count
}
panic()
的普遍存在并不正确。 - Sean Lindo