gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

value.go (882B)


      1 package errors
      2 
      3 import "errors"
      4 
      5 // WithValue wraps err to store given key-value pair, accessible via Value() function.
      6 func WithValue(err error, key any, value any) error {
      7 	if err == nil {
      8 		panic("nil error")
      9 	}
     10 	return &errWithValue{
     11 		err: err,
     12 		key: key,
     13 		val: value,
     14 	}
     15 }
     16 
     17 // Value searches for value stored under given key in error chain.
     18 func Value(err error, key any) any {
     19 	var e *errWithValue
     20 
     21 	if !errors.As(err, &e) {
     22 		return nil
     23 	}
     24 
     25 	return e.Value(key)
     26 }
     27 
     28 type errWithValue struct {
     29 	err error
     30 	key any
     31 	val any
     32 }
     33 
     34 func (e *errWithValue) Error() string {
     35 	return e.err.Error()
     36 }
     37 
     38 func (e *errWithValue) Is(target error) bool {
     39 	return e.err == target
     40 }
     41 
     42 func (e *errWithValue) Unwrap() error {
     43 	return Unwrap(e.err)
     44 }
     45 
     46 func (e *errWithValue) Value(key any) any {
     47 	for {
     48 		if key == e.key {
     49 			return e.val
     50 		}
     51 
     52 		if !errors.As(e.err, &e) {
     53 			return nil
     54 		}
     55 	}
     56 }