2 回答

TA貢獻1799條經驗 獲得超8個贊
conn.Read
一般來說,可重試的操作不會出現任何錯誤。該界面的大多數使用io.Reader
都會假設所有錯誤都是最終的。
任何net
確??芍卦嚨陌e誤都將符合接口net.Error
,并公開一個Temporary
方法。
這最常在Accept
循環中使用,就像 http 包中的這個解釋示例一樣
for {
? ? rw, e := l.Accept()
? ? if e != nil {
? ? ? ? if ne, ok := e.(net.Error); ok && ne.Temporary() {
? ? ? ? ? ? if tempDelay == 0 {
? ? ? ? ? ? ? ? tempDelay = 5 * time.Millisecond
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? tempDelay *= 2
? ? ? ? ? ? }
? ? ? ? ? ? if max := 1 * time.Second; tempDelay > max {
? ? ? ? ? ? ? ? tempDelay = max
? ? ? ? ? ? }
? ? ? ? ? ? time.Sleep(tempDelay)
? ? ? ? ? ? continue
? ? ? ? }
? ? ? ? return e
? ? }
}
任何其他可能的情況都需要在了解協議和當前情況的情況下根據個人情況進行處理。

TA貢獻1865條經驗 獲得超7個贊
超時是從net.TCPConn讀取時唯一可恢復的錯誤,并且只有在連接上設置讀取截止時間時才會返回該錯誤。
使用?Error.Temporary()檢查重試時可能解決的錯誤,并使用Error.Timeout()檢查超時:
?n, err := c.Read(buf)
?// process buf[:n] bytes
?if e.(net.Error); ok && e.Timeout() && e.Temporary() {
? ? // handle recoverable read deadline expiration
?} else if err != nil {
? ? // handle other errors
?}

TA貢獻1853條經驗 獲得超18個贊
查看net包的具體錯誤類型https://golang.org/pkg/net/#OpError
它提供了一種特定的Temporary()
方法來確定是否是非終止錯誤。
要手動找出哪個錯誤,Temporary
您必須檢查網絡、操作系統和其他一些內部包中定義的每個錯誤。
要以編程方式檢查臨時錯誤,您可以聲明自己的 local ,或者可以依賴 net 包https://golang.org/pkg/net/#Errortemporary interface{ Temporary() bool }
提供的此接口
該OpError.Temporary
方法測試其內部錯誤是否實現了net.temporary
接口(https://golang.org/src/net/net.go?s=16056:16090#L501Temporary()
),如果是則返回內部錯誤的調用結果,例如https://golang.org/src/net/net.go?s=19122:19157#L605。
我不確定您正在考慮哪種讀取重試,但是,內部 fd.read 方法再次實現重試 https://golang.org/src/internal/poll/fd_unix.go#L165
- 2 回答
- 0 關注
- 155 瀏覽
添加回答
舉報