在一个地方处理重复的错误案例

时间:2015-01-12 17:28:29

标签: error-handling go

我正在编写一个将多个字段的结构写入TCP连接的函数。有没有办法在一个地方处理错误,比如在Java中捕获异常?

我的实现看起来像,

func writeFrame(frame *Frame, conn net.Conn) error {
    bo := binary.BigEndian
    if err := binary.Write(conn, bo, frame.ype); err != nil {
        return err
    }
    if err := binary.Write(conn, bo, frame.id); err != nil {
        return err
    }
    if err := binary.Write(conn, bo, frame.seq); err != nil {
        return err
    }

    if err := binary.Write(conn, bo, uint32(len(frame.arg1))); err != nil {
        return err
    }
    if err := binary.Write(conn, bo, uint32(len(frame.arg2))); err != nil {
        return err
    }
    if err := binary.Write(conn, bo, uint32(len(frame.arg3))); err != nil {
        return err
    }

    var csum uint32
    if err := binary.Write(conn, bo, csum); err != nil {
        return err
    }

    if _, err := conn.Write(frame.arg1); err != nil {
        return err
    }
    if _, err := conn.Write(frame.arg2); err != nil {
        return err
    }
    if _, err := conn.Write(frame.arg3); err != nil {
        return err
    }
    return nil
}

1 个答案:

答案 0 :(得分:2)

您可以使用bufio.Writer。如果发生任何错误,将来Write会返回相同的错误并被忽略。

func writeFrame(frame *Frame, conn net.Conn) error {
    bo := binary.BigEndian

    w := bufio.NewWriter(conn)

    binary.Write(w, bo, frame.ype)
    binary.Write(w, bo, frame.id)
    binary.Write(w, bo, frame.seq)

    binary.Write(w, bo, uint32(len(frame.arg1)))
    binary.Write(w, bo, uint32(len(frame.arg2)))
    binary.Write(w, bo, uint32(len(frame.arg3)))

    var csum uint32
    binary.Write(w, bo, csum)

    w.Write(frame.arg1)
    w.Write(frame.arg2)
    w.Write(frame.arg3)

    // Write outstanding data to conn and return an error if any occured
    return w.Flush()
}