Unify error checking by introducing error codes

This commit is contained in:
V2Ray
2015-09-25 00:17:44 +02:00
parent 1995594b98
commit 08f85fc9b7
7 changed files with 124 additions and 53 deletions
+38 -7
View File
@@ -4,55 +4,86 @@ import (
"fmt"
)
func HasCode(err error, code int) bool {
if errWithCode, ok := err.(ErrorWithCode); ok {
return errWithCode.Code() == code
}
return false
}
type ErrorWithCode interface {
error
Code() int
}
type ErrorCode int
func (code ErrorCode) Code() int {
return int(code)
}
func (code ErrorCode) Prefix() string {
return fmt.Sprintf("[Error 0x%04X] ", code.Code())
}
type AuthenticationError struct {
ErrorCode
AuthDetail interface{}
}
func NewAuthenticationError(detail interface{}) AuthenticationError {
return AuthenticationError{
ErrorCode: 1,
AuthDetail: detail,
}
}
func (err AuthenticationError) Error() string {
return fmt.Sprintf("[Error 0x0001] Invalid auth %v", err.AuthDetail)
return fmt.Sprintf("%sInvalid auth %v", err.Prefix(), err.AuthDetail)
}
type ProtocolVersionError struct {
ErrorCode
Version int
}
func NewProtocolVersionError(version int) ProtocolVersionError {
return ProtocolVersionError{
Version: version,
ErrorCode: 2,
Version: version,
}
}
func (err ProtocolVersionError) Error() string {
return fmt.Sprintf("[Error 0x0002] Invalid version %d", err.Version)
return fmt.Sprintf("%sInvalid version %d", err.Prefix(), err.Version)
}
type CorruptedPacketError struct {
ErrorCode
}
var corruptedPacketErrorInstance = CorruptedPacketError{ErrorCode: 3}
func NewCorruptedPacketError() CorruptedPacketError {
return CorruptedPacketError{}
return corruptedPacketErrorInstance
}
func (err CorruptedPacketError) Error() string {
return "[Error 0x0003] Corrupted packet."
return err.Prefix() + "Corrupted packet."
}
type IPFormatError struct {
ErrorCode
IP []byte
}
func NewIPFormatError(ip []byte) IPFormatError {
return IPFormatError{
IP: ip,
ErrorCode: 4,
IP: ip,
}
}
func (err IPFormatError) Error() string {
return fmt.Sprintf("[Error 0x0004] Invalid IP %v", err.IP)
return fmt.Sprintf("%sInvalid IP %v", err.Prefix(), err.IP)
}
+23
View File
@@ -0,0 +1,23 @@
package errors_test
import (
"testing"
"github.com/v2ray/v2ray-core/common/errors"
"github.com/v2ray/v2ray-core/testing/unit"
)
type MockError struct {
errors.ErrorCode
}
func (err MockError) Error() string {
return "This is a fake error."
}
func TestHasCode(t *testing.T) {
assert := unit.Assert(t)
err := MockError{ErrorCode: 101}
assert.Error(err).HasCode(101)
}