codeberg.org/gruf/go-errors/v2@v2.3.1/value.go (about)

     1  package errors
     2  
     3  // WithValue wraps err to store given key-value pair, accessible via Value() function.
     4  func WithValue(err error, key any, value any) error {
     5  	if err == nil {
     6  		panic("nil error")
     7  	}
     8  	var kvs []kv
     9  	if e := AsV2[*errWithValues](err); e != nil {
    10  		kvs = e.kvs
    11  	}
    12  	return &errWithValues{
    13  		err: err,
    14  		kvs: append(kvs, kv{key, value}),
    15  	}
    16  }
    17  
    18  // Value searches for value stored under given key in error chain.
    19  func Value(err error, key any) any {
    20  	if e := AsV2[*errWithValues](err); e != nil {
    21  		return e.Value(key)
    22  	}
    23  	return nil
    24  }
    25  
    26  // simple key-value type.
    27  type kv struct{ k, v any }
    28  
    29  // errWithValues wraps an error to provide key-value storage.
    30  type errWithValues struct {
    31  	err error
    32  	kvs []kv
    33  }
    34  
    35  func (e *errWithValues) Error() string {
    36  	return e.err.Error()
    37  }
    38  
    39  func (e *errWithValues) Unwrap() error {
    40  	return e.err
    41  }
    42  
    43  func (e *errWithValues) Value(key any) any {
    44  	for i := range e.kvs {
    45  		if e.kvs[i].k == key {
    46  			return e.kvs[i].v
    47  		}
    48  	}
    49  	return nil
    50  }