fix error in gerror.HasCode (#3277)

This commit is contained in:
John Guo 2024-01-24 20:36:32 +08:00 committed by GitHub
parent 4fb739615b
commit e6d61e6e14
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 7 additions and 3 deletions

View File

@ -109,7 +109,7 @@ func WrapCodeSkipf(code gcode.Code, skip int, err error, format string, args ...
} }
} }
// Code returns the error code of current error. // Code returns the error code of `current error`.
// It returns `CodeNil` if it has no error code neither it does not implement interface Code. // It returns `CodeNil` if it has no error code neither it does not implement interface Code.
func Code(err error) gcode.Code { func Code(err error) gcode.Code {
if err == nil { if err == nil {
@ -129,8 +129,8 @@ func HasCode(err error, code gcode.Code) bool {
if err == nil { if err == nil {
return false return false
} }
if e, ok := err.(ICode); ok { if e, ok := err.(ICode); ok && code == e.Code() {
return code == e.Code() return true
} }
if e, ok := err.(IUnwrap); ok { if e, ok := err.(IUnwrap); ok {
return HasCode(e.Unwrap(), code) return HasCode(e.Unwrap(), code)

View File

@ -433,10 +433,14 @@ func Test_HashCode(t *testing.T) {
err2 := gerror.WrapCode(gcode.CodeNotAuthorized, err1, "2") err2 := gerror.WrapCode(gcode.CodeNotAuthorized, err1, "2")
err3 := gerror.Wrap(err2, "3") err3 := gerror.Wrap(err2, "3")
err4 := gerror.Wrap(err3, "4") err4 := gerror.Wrap(err3, "4")
err5 := gerror.WrapCode(gcode.CodeInvalidParameter, err4, "5")
t.Assert(gerror.HasCode(err1, gcode.CodeNotAuthorized), false) t.Assert(gerror.HasCode(err1, gcode.CodeNotAuthorized), false)
t.Assert(gerror.HasCode(err2, gcode.CodeNotAuthorized), true) t.Assert(gerror.HasCode(err2, gcode.CodeNotAuthorized), true)
t.Assert(gerror.HasCode(err3, gcode.CodeNotAuthorized), true) t.Assert(gerror.HasCode(err3, gcode.CodeNotAuthorized), true)
t.Assert(gerror.HasCode(err4, gcode.CodeNotAuthorized), true) t.Assert(gerror.HasCode(err4, gcode.CodeNotAuthorized), true)
t.Assert(gerror.HasCode(err5, gcode.CodeNotAuthorized), true)
t.Assert(gerror.HasCode(err5, gcode.CodeInvalidParameter), true)
t.Assert(gerror.HasCode(err5, gcode.CodeInternalError), false)
}) })
} }