dousong3760 2019-08-06 17:54
浏览 356
已采纳

尝试了monad模式,但仍然有重复的错误处理

I read Rob Pike's post but it only works for repetitive loops. I, on the other hand, have this. Notice how I added the err field, accessible via the Error() method, in a futile attempt to reduce the if errs.

The code above is simpler, but the ReadRLP() function is no different from just returning a err. Is there some pattern that can help with this?

type namePreclaimRLP struct {
    ObjectTag         uint
    RlpMessageVersion uint
    AccountID         []uint8
    AccountNonce      uint64
    CommitmentID      []uint8
    Fee               big.Int
    TTL               uint64
    err               error
}

func (n *namePreclaimRLP) ReadRLP(s *rlp.Stream) (aID, cID string) {
    blob, err := s.Raw()
    if err != nil {
        n.err = err
    }
    err = rlp.DecodeBytes(blob, n)
    if err != nil {
        n.err = err
    }
    _, aID, err = readIDTag(n.AccountID)
    if err != nil {
        n.err = err
    }
    _, cID, err = readIDTag(n.CommitmentID)
    if err != nil {
        n.err = err
    }
    return aID, cID
}

func (n *namePreclaimRLP) Error() (err error) {
    return n.err
}
  • 写回答

2条回答 默认 最新

  • douzhanrun0497 2019-08-06 18:13
    关注

    Your code doesn't compile as written (there are a lot of missing types), so I can't fully test this code, but I would expect something along these lines, returning err in the typical Go approach, rather than making it part of another type, which is unusual and a bit confusing:

    func (n *namePreclaimRLP) ReadRLP(s *rlp.Stream) (aID, cID string, err error) {
        var blob SomeType // Depends on what blob actually is
        if blob, err = s.Raw(); err != nil {
            return
        }
    
        if err = rlp.DecodeBytes(blob, n); err != nil {
            return
        }
    
        if _, aID, err = readIDTag(n.AccountID); err != nil {
            return
        }
    
        _, cID, err = readIDTag(n.CommitmentID)
    
        return
    }
    

    I'd delete your Error() function here and the err field. namePreclaimRLP is not a kind of error. It feels you're abusing the interface there.

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

报告相同问题?

悬赏问题

  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题