github.com/haraldrudell/parl@v0.4.176/nil-error.go (about)

     1  /*
     2  © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package parl
     7  
     8  import (
     9  	"fmt"
    10  
    11  	"github.com/haraldrudell/parl/perrors"
    12  	"github.com/haraldrudell/parl/pruntime"
    13  )
    14  
    15  const (
    16  	// count frame of [parl.NilError]
    17  	nilErrorFrames = 1
    18  )
    19  
    20  // ErrNil is used with [errors.Is] to detect that a panic or error value was caused
    21  // by a value that cannot be nil, such as a function argument to a new function,
    22  // was nil
    23  //   - —
    24  //   - a nilValue type implements:
    25  //   - — a dummy NilValueError method
    26  //   - — an Is method returning true for errors implementing a NilValueError method
    27  //
    28  // Usage:
    29  //
    30  //	if errors.Is(err, parl.ErrNil) { …
    31  var ErrNil = &nilValue{"value"}
    32  
    33  // NilError returns an error used with panic() indicating that a value that cannot be nil,
    34  // such as a function argument to a new function, was nil
    35  //   - such panics typically indicate compile-time issues with code
    36  //
    37  // Usage:
    38  //
    39  //	func NewX(xValue *int) (x *X) {
    40  //	  if xValue == nil {
    41  //	    panic(parl.NilError("xValue")) // “somePackage.NewX xValue cannot be nil”
    42  func NilError(valueName string) (err error) {
    43  	var cL = pruntime.NewCodeLocation(nilErrorFrames)
    44  	return perrors.Stackn(&nilValue{
    45  		s: fmt.Sprintf("%s %s cannot be nil",
    46  			cL.PackFunc(), // “somePackage.NewX”
    47  			valueName,     // “xValue”
    48  		)}, nilErrorFrames)
    49  }
    50  
    51  var _ nilValueIface = &nilValue{}
    52  
    53  // nilValue is the type for NilError errors
    54  type nilValue struct{ s string }
    55  
    56  // nilValueIface looks for the NilValueError method
    57  type nilValueIface interface{ NilValueError() }
    58  
    59  // Error return the error message
    60  //   - allows nilValue to implement the error interface
    61  func (e *nilValue) Error() (message string) { return e.s }
    62  
    63  // Is method allowing for nilValue values to detect other nilValues
    64  func (e *nilValue) Is(err error) (is bool) {
    65  	_, is = err.(nilValueIface)
    66  	return
    67  }
    68  
    69  // dummy method NilValueError
    70  func (e *nilValue) NilValueError() {}