2023-01-17 11:25:13 +00:00
|
|
|
package errors
|
|
|
|
|
|
|
|
// WithValue wraps err to store given key-value pair, accessible via Value() function.
|
|
|
|
func WithValue(err error, key any, value any) error {
|
|
|
|
if err == nil {
|
|
|
|
panic("nil error")
|
|
|
|
}
|
2023-11-30 16:22:34 +00:00
|
|
|
var kvs []kv
|
|
|
|
if e := AsV2[*errWithValues](err); e != nil {
|
|
|
|
kvs = e.kvs
|
|
|
|
}
|
|
|
|
return &errWithValues{
|
2023-01-17 11:25:13 +00:00
|
|
|
err: err,
|
2023-11-30 16:22:34 +00:00
|
|
|
kvs: append(kvs, kv{key, value}),
|
2023-01-17 11:25:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Value searches for value stored under given key in error chain.
|
|
|
|
func Value(err error, key any) any {
|
2023-11-30 16:22:34 +00:00
|
|
|
if e := AsV2[*errWithValues](err); e != nil {
|
|
|
|
return e.Value(key)
|
2023-01-17 11:25:13 +00:00
|
|
|
}
|
2023-11-30 16:22:34 +00:00
|
|
|
return nil
|
2023-01-17 11:25:13 +00:00
|
|
|
}
|
|
|
|
|
2023-11-30 16:22:34 +00:00
|
|
|
// simple key-value type.
|
|
|
|
type kv struct{ k, v any }
|
|
|
|
|
|
|
|
// errWithValues wraps an error to provide key-value storage.
|
|
|
|
type errWithValues struct {
|
2023-01-17 11:25:13 +00:00
|
|
|
err error
|
2023-11-30 16:22:34 +00:00
|
|
|
kvs []kv
|
2023-01-17 11:25:13 +00:00
|
|
|
}
|
|
|
|
|
2023-11-30 16:22:34 +00:00
|
|
|
func (e *errWithValues) Error() string {
|
2023-01-17 11:25:13 +00:00
|
|
|
return e.err.Error()
|
|
|
|
}
|
|
|
|
|
2023-11-30 16:22:34 +00:00
|
|
|
func (e *errWithValues) Unwrap() error {
|
|
|
|
return e.err
|
2023-01-17 11:25:13 +00:00
|
|
|
}
|
|
|
|
|
2023-11-30 16:22:34 +00:00
|
|
|
func (e *errWithValues) Value(key any) any {
|
|
|
|
for i := range e.kvs {
|
|
|
|
if e.kvs[i].k == key {
|
|
|
|
return e.kvs[i].v
|
2023-01-17 11:25:13 +00:00
|
|
|
}
|
|
|
|
}
|
2023-11-30 16:22:34 +00:00
|
|
|
return nil
|
2023-01-17 11:25:13 +00:00
|
|
|
}
|