我创建了一个“基础”存储库结构,供独立使用和嵌入式使用(例如,与CustomerRepository一起使用),以避免必须一直检查错误,并避免为Gorp创建抽象(数据库工具包),并稍微创建一个API来我喜欢
我在此基本结构中检查错误,并且发现了错误,就像我认为的那样,它表明存在开发错误,并且代码也可能会出现恐慌,例如验证等,应该在数据到达存储库之前发生。
我发现了这个问题Go Error Handling Techniques,但是它并没有涵盖将错误包装在基本结构中的方法,就像我已经做过的一样,只是惊慌失措。
是我惯用的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
}
惯用的方法是返回带有相关类型值的错误,即
func (list ...interface{}) (v int46, err error) {}
...,然后在调用这些函数的地方检查err!= nil。
最终,使用panic()将导致类似异常的错误处理和更多样板代码(如果您认为错误是可恢复的)。
惯用的错误处理在Go中很冗长,但比模拟异常要少(从根本上说,这不是“ Go方式”)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句