github.com/alloyzeus/go-azfl@v0.0.0-20231220071816-9740126a2d07/errors/context.go (about) 1 package errors 2 3 import "strings" 4 5 type ContextError interface { 6 CallError 7 ContextError() ContextError 8 } 9 10 func IsContextError(err error) bool { 11 _, ok := err.(ContextError) 12 return ok 13 } 14 15 func Context(details error, fields ...EntityError) ContextError { 16 return &contextError{inner: details, fields: copyFieldSet(fields)} 17 } 18 19 func ContextFields(fields ...EntityError) ContextError { 20 return &contextError{ 21 fields: copyFieldSet(fields), 22 } 23 } 24 25 func ContextUnspecified() ContextError { 26 return &contextError{inner: ErrValueUnspecified} 27 } 28 29 func IsContextUnspecifiedError(err error) bool { 30 if !IsContextError(err) { 31 return false 32 } 33 if desc := UnwrapDescriptor(err); desc != nil { 34 return desc == ErrValueUnspecified 35 } 36 return false 37 } 38 39 type contextError struct { 40 inner error 41 fields []EntityError 42 } 43 44 var ( 45 _ error = &contextError{} 46 _ CallError = &contextError{} 47 _ ContextError = &contextError{} 48 _ Unwrappable = &contextError{} 49 ) 50 51 func (e *contextError) Error() string { 52 suffix := e.fieldErrorsAsString() 53 if suffix != "" { 54 suffix = ": " + suffix 55 } 56 57 if errMsg := e.innerMsg(); errMsg != "" { 58 return "context " + errMsg + suffix 59 } 60 return "context invalid" + suffix 61 } 62 63 func (e *contextError) CallError() CallError { return e } 64 func (e *contextError) ContextError() ContextError { return e } 65 func (e *contextError) Unwrap() error { return e.inner } 66 67 func (e *contextError) innerMsg() string { 68 if e.inner != nil { 69 return e.inner.Error() 70 } 71 return "" 72 } 73 74 func (e contextError) fieldErrorsAsString() string { 75 if flen := len(e.fields); flen > 0 { 76 parts := make([]string, 0, flen) 77 for _, sub := range e.fields { 78 parts = append(parts, sub.Error()) 79 } 80 return strings.Join(parts, ", ") 81 } 82 return "" 83 } 84 85 func (e *contextError) Descriptor() ErrorDescriptor { 86 if e == nil { 87 return nil 88 } 89 if desc, ok := e.inner.(ErrorDescriptor); ok { 90 return desc 91 } 92 if desc := UnwrapDescriptor(e.inner); desc != nil { 93 return desc 94 } 95 return nil 96 }