dsk95913 2014-01-21 17:47
浏览 54
已采纳

Golang惯用错误处理

I have created a "base" repository struct for standalone and embedded use (e.g with CustomerRepository) to avoid having to check errors all the time, and to create an abstraction for Gorp (the database toolkit), and to create an API slightly more to my liking.

I check for errors in this base struct and panic if one is found, as if one does exist in my opinion it then indicates a dev error and the code may as well panic, seeing as validation etc. should happen before data gets to the Repository.

I found this question Go Error Handling Techniques, but it doesn't cover wrapping errors up in a base struct like I have done and just panicking.

Is what I have done idiomatic 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
}
  • 写回答

2条回答 默认 最新

  • douke9379 2014-01-21 17:55
    关注

    The idiomatic way would be to return the error with the associated type value, i.e.

    func (list ...interface{}) (v int46, err error) {}
    

    ... and subsequently check err != nil where these functions are called.

    Ultimately using panic() will result in Exception-like error handling and more boiler-plate code (if you deem the error to be recoverable).

    Idiomatic error handling is verbose in Go, but less so than emulating exceptions (which is fundamentally not the "Go way").

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集