2 回答

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超8個(gè)贊
conn.Read
一般來(lái)說(shuō),可重試的操作不會(huì)出現(xiàn)任何錯(cuò)誤。該界面的大多數(shù)使用io.Reader
都會(huì)假設(shè)所有錯(cuò)誤都是最終的。
任何net
確??芍卦嚨陌e(cuò)誤都將符合接口net.Error
,并公開(kāi)一個(gè)Temporary
方法。
這最常在Accept
循環(huán)中使用,就像 http 包中的這個(gè)解釋示例一樣
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
? ? }
}
任何其他可能的情況都需要在了解協(xié)議和當(dāng)前情況的情況下根據(jù)個(gè)人情況進(jìn)行處理。

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
超時(shí)是從net.TCPConn讀取時(shí)唯一可恢復(fù)的錯(cuò)誤,并且只有在連接上設(shè)置讀取截止時(shí)間時(shí)才會(huì)返回該錯(cuò)誤。
使用?Error.Temporary()檢查重試時(shí)可能解決的錯(cuò)誤,并使用Error.Timeout()檢查超時(shí):
?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貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超18個(gè)贊
查看net包的具體錯(cuò)誤類(lèi)型https://golang.org/pkg/net/#OpError
它提供了一種特定的Temporary()
方法來(lái)確定是否是非終止錯(cuò)誤。
要手動(dòng)找出哪個(gè)錯(cuò)誤,Temporary
您必須檢查網(wǎng)絡(luò)、操作系統(tǒng)和其他一些內(nèi)部包中定義的每個(gè)錯(cuò)誤。
要以編程方式檢查臨時(shí)錯(cuò)誤,您可以聲明自己的 local ,或者可以依賴(lài) net 包https://golang.org/pkg/net/#Errortemporary interface{ Temporary() bool }
提供的此接口
該OpError.Temporary
方法測(cè)試其內(nèi)部錯(cuò)誤是否實(shí)現(xiàn)了net.temporary
接口(https://golang.org/src/net/net.go?s=16056:16090#L501Temporary()
),如果是則返回內(nèi)部錯(cuò)誤的調(diào)用結(jié)果,例如https://golang.org/src/net/net.go?s=19122:19157#L605。
我不確定您正在考慮哪種讀取重試,但是,內(nèi)部 fd.read 方法再次實(shí)現(xiàn)重試 https://golang.org/src/internal/poll/fd_unix.go#L165
- 2 回答
- 0 關(guān)注
- 152 瀏覽
添加回答
舉報(bào)