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条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值