douyicao2199 2019-05-30 17:03
浏览 18

我可以使用指向“错误”的指针来捕获返回错误吗?

I am writing some transaction begin/commit/rollback functions, and I want to pair the block to prevent forgot commit

I write like this:


func (foo *Foo) Bar() (err error) {

  foo.Begin()
  defer foo.End(&err)

  //some business code

  return
}

func (foo *Foo) End(eptr *error) {
  // if recover
  if r := recover(); r != nil {
    debug.PrintStack()
    *eptr = r.(error)
  }

  var err = *eptr
  if err != nil {
    foo.Rollback()
  } else {
    foo.Commit()
  }
}

It works, but it uses the "pointer to interface", I cannot find the specifications about pointer to interface.

So, I am not sure this code is OK enough. Could you give some suggestions?


thanks to teyzer and Corey Ogburn, this is my fixed solution:


func (foo *Foo) Bar() (err error) {

  foo.Begin()
  defer func() { foo.End(err) }()
  defer func() {
   if r := recover(); r != nil {
      debug.PrintStack()
      err = makeError(r)
   }
  } ()

  //some business code

  return
}

func (foo *Foo) End(err error) {  
  if err != nil {
    foo.Rollback()
  } else {
    foo.Commit()
  }
}

  • 写回答

2条回答 默认 最新

  • dongtang8678 2019-05-30 17:13
    关注

    The usual approach is to use recover() to catch any panics. What you have is very similar to that approach. Check out the Go wiki about Panic and Recover

    func (foo *Foo) Bar() (err error) {
    
      foo.Begin()
      defer foo.End()
    
      //some business code
      err = fmt.Errorf("oh no, an error!") // set error so that Bar returns it even though it's caught
      panic(err)
    
      return
    }
    
    func (foo *Foo) End() {
      err := recover()
      if err != nil {
        foo.Rollback()
      } else {
        foo.Commit()
      }
    }
    

    https://play.golang.org/p/m_kpT5xtwe2

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作