github.com/haraldrudell/parl@v0.4.176/perrors/is.go (about)

     1  /*
     2  © 2020–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package perrors
     7  
     8  import "fmt"
     9  
    10  const (
    11  	isStackFrames = 1
    12  )
    13  
    14  func Is2(errp *error, e error, format string, a ...interface{}) (isBad bool) {
    15  	if e == nil {
    16  		return // no error exit
    17  	} else if !HasStack(e) {
    18  		e = Stackn(e, isStackFrames)
    19  	}
    20  	Is(&e, format, a...)
    21  	if errp != nil {
    22  		*errp = AppendError(*errp, e)
    23  	}
    24  	return true
    25  }
    26  
    27  func Is2PF(errp *error, e error, format string, a ...interface{}) (isBad bool) {
    28  	if e == nil {
    29  		return // no error exit
    30  	} else if !HasStack(e) {
    31  		e = Stackn(e, isStackFrames)
    32  	}
    33  	PF := PackFuncN(isStackFrames)
    34  	if format == "" {
    35  		e = fmt.Errorf("%s %w", PF, e)
    36  	} else {
    37  		e = fmt.Errorf("%s "+format, append([]interface{}{PF}, a...)...)
    38  	}
    39  	if errp != nil {
    40  		*errp = AppendError(*errp, e)
    41  	}
    42  	return true
    43  }
    44  
    45  // Is returns true if *errp contains a non-nil error
    46  //   - if return value is true and format is not empty string, *errp is updated with
    47  //     fmt.Errorf using format and a, typically including “%w” and an error
    48  //   - if *errp is non-nil and does not have a stack, a stack is inserted into
    49  //     its error chain
    50  //   - errp cannot be nil or panic
    51  func Is(errp *error, format string, a ...interface{}) (isBad bool) {
    52  	if errp == nil {
    53  		panic(NewPF("errp nil"))
    54  	}
    55  	err := *errp
    56  	if err == nil {
    57  		return // no error exit
    58  	}
    59  	if format != "" {
    60  		err = fmt.Errorf(format, a...)
    61  	}
    62  	if !HasStack(err) {
    63  		err = Stackn(err, isStackFrames)
    64  	}
    65  	*errp = err
    66  	return true
    67  }
    68  
    69  func IsPF(errp *error, format string, a ...interface{}) (isBad bool) {
    70  	if errp == nil {
    71  		panic(NewPF("errp nil"))
    72  	}
    73  	err := *errp
    74  	if err == nil {
    75  		return false // no error exit
    76  	}
    77  	PF := PackFuncN(isStackFrames)
    78  	if format == "" {
    79  		err = fmt.Errorf("%s %w", PF, err)
    80  	} else {
    81  		err = fmt.Errorf("%s "+format, append([]interface{}{PF}, a...)...)
    82  	}
    83  	if !HasStack(err) {
    84  		err = Stackn(err, isStackFrames)
    85  	}
    86  	*errp = err
    87  	return true
    88  }