errors: add CodeIn helper func
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
parent
1db505decd
commit
c5aeaf6db7
@ -233,6 +233,27 @@ func Equal(err1 error, err2 error) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// CodeIn return true if err has specified code
|
||||
func CodeIn(err interface{}, codes ...int32) bool {
|
||||
var code int32
|
||||
switch verr := err.(type) {
|
||||
case *Error:
|
||||
code = verr.Code
|
||||
case int32:
|
||||
code = verr
|
||||
default:
|
||||
return false
|
||||
}
|
||||
|
||||
for _, check := range codes {
|
||||
if code == check {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// FromError try to convert go error to *Error
|
||||
func FromError(err error) *Error {
|
||||
if verr, ok := err.(*Error); ok && verr != nil {
|
||||
|
@ -96,3 +96,20 @@ func TestErrors(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func TestCodeIn(t *testing.T) {
|
||||
err := InternalServerError("id", "%s", "msg")
|
||||
|
||||
if ok := CodeIn(err, 400, 500); !ok {
|
||||
t.Fatalf("CodeIn not works: %v", err)
|
||||
}
|
||||
|
||||
if ok := CodeIn(err.(*Error).Code, 500); !ok {
|
||||
t.Fatalf("CodeIn not works: %v", err)
|
||||
}
|
||||
|
||||
if ok := CodeIn(err, 100); ok {
|
||||
t.Fatalf("CodeIn not works: %v", err)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user