ServerError type check before EOF string comparison

This commit is contained in:
Pierre Cauchois 2020-09-19 01:59:04 +00:00
parent aa1875c3c7
commit 352cf930fc
2 changed files with 15 additions and 8 deletions

View File

@ -2,7 +2,9 @@ package lib
import ( import (
"errors" "errors"
"fmt"
"io" "io"
"net/rpc"
"strings" "strings"
"github.com/hashicorp/yamux" "github.com/hashicorp/yamux"
@ -20,10 +22,17 @@ func IsErrEOF(err error) bool {
errStr := err.Error() errStr := err.Error()
if strings.Contains(errStr, yamuxStreamClosed) || if strings.Contains(errStr, yamuxStreamClosed) ||
strings.Contains(errStr, yamuxSessionShutdown) || strings.Contains(errStr, yamuxSessionShutdown) {
strings.HasSuffix(errStr, io.EOF.Error()) {
return true return true
} }
if srvErr, ok := err.(rpc.ServerError); ok {
return strings.HasSuffix(srvErr.Error(), fmt.Sprintf(": %s", io.EOF.Error()))
}
if srvErr, ok := errors.Unwrap(err).(rpc.ServerError); ok {
return strings.HasSuffix(srvErr.Error(), fmt.Sprintf(": %s", io.EOF.Error()))
}
return false return false
} }

View File

@ -3,6 +3,7 @@ package lib
import ( import (
"fmt" "fmt"
"io" "io"
"net/rpc"
"testing" "testing"
"github.com/hashicorp/yamux" "github.com/hashicorp/yamux"
@ -15,19 +16,16 @@ func TestErrIsEOF(t *testing.T) {
err error err error
}{ }{
{name: "EOF", err: io.EOF}, {name: "EOF", err: io.EOF},
{name: "Wrapped EOF", err: fmt.Errorf("test: %w", io.EOF)},
{name: "yamuxStreamClosed", err: yamux.ErrStreamClosed}, {name: "yamuxStreamClosed", err: yamux.ErrStreamClosed},
{name: "yamuxSessionShutdown", err: yamux.ErrSessionShutdown}, {name: "yamuxSessionShutdown", err: yamux.ErrSessionShutdown},
{name: "ServerError(___: EOF)", err: rpc.ServerError(fmt.Sprintf("rpc error: %s", io.EOF.Error()))},
{name: "Wrapped ServerError(___: EOF)", err: fmt.Errorf("rpc error: %w", rpc.ServerError(fmt.Sprintf("rpc error: %s", io.EOF.Error())))},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
require.True(t, IsErrEOF(tt.err)) require.True(t, IsErrEOF(tt.err))
}) })
t.Run(fmt.Sprintf("Wrapped %s", tt.name), func(t *testing.T) {
require.True(t, IsErrEOF(fmt.Errorf("test: %w", tt.err)))
})
t.Run(fmt.Sprintf("String suffix is %s", tt.name), func(t *testing.T) {
require.True(t, IsErrEOF(fmt.Errorf("rpc error: %s", tt.err.Error())))
})
} }
} }