github.com/haraldrudell/parl@v0.4.176/perrors/errorglue/error-data.go (about) 1 /* 2 © 2020–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package errorglue 7 8 import ( 9 "fmt" 10 ) 11 12 // errorData contains single key-value pair strings, both that may be empty 13 // - rich error: has ChainString method 14 // - [github.com/haraldrudell/parl/perrors.ErrorData] aggregates: 15 // - — values with empty key into a slice 16 // - — values with non-empty key into a map, overwriting older values 17 // - [github.com/haraldrudell/parl/perrors/errorglue.ChainString] with formats: 18 // - — [github.com/haraldrudell/parl/perrors/errorglue.LongFormat] or 19 // - — [github.com/haraldrudell/parl/perrors/errorglue.LongSuffix] 20 // - — prints key:value with each error 21 type errorData struct { 22 RichError 23 key string 24 value string 25 } 26 27 var _ error = &errorData{} // errorData behaves like an error 28 var _ ErrorHasData = &errorData{} // errorData implements the error116.ErrorHasData interface 29 var _ Wrapper = &errorData{} // errorData has an error chain 30 var _ fmt.Formatter = &errorData{} // errorData can be used with fmt.Printf %v 31 var _ ChainStringer = &errorData{} // errorData can be used by error116.ChainStringer() 32 33 // NewErrorData returns an error containg a key/value pair 34 func NewErrorData(err error, key, value string) (e2 error) { 35 return &errorData{*newRichError(err), key, value} 36 } 37 38 // KeyValue returns the assoiacted key/value pair 39 func (e *errorData) KeyValue() (key, value string) { 40 if e == nil { 41 return 42 } 43 return e.key, e.value 44 } 45 46 // ChainString returns a string representation 47 // - invoked by [github.com/haraldrudell/parl/perrors/errorglue.ChainString] 48 func (e *errorData) ChainString(format CSFormat) (s string) { 49 50 // nil case 51 if e == nil { 52 return 53 } 54 55 switch format { 56 case ShortSuffix: 57 return 58 case DefaultFormat, ShortFormat: // no data 59 s = e.Error() 60 return 61 case LongSuffix: 62 case LongFormat: 63 s = fmt.Sprintf("%s [%T]", e.Error(), e) 64 default: 65 return 66 } 67 // LongSuffix or LongFormat 68 69 // build “key: value” 70 // - may be empty 71 var keyValue = e.value 72 if e.key != "" { 73 keyValue = e.key + ":\x20" + keyValue 74 } 75 76 // append to s 77 if s == "" { 78 s = keyValue 79 } else if keyValue != "" { 80 s = s + "\n" + keyValue 81 } 82 83 return 84 }