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

     1  /*
     2  © 2021–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package errorglue
     7  
     8  import (
     9  	"fmt"
    10  	"io"
    11  	"strconv"
    12  )
    13  
    14  // RichError is an error chain that behaves like fmt.Formatter.
    15  // this allows for custom print-outs using %+v and %-v
    16  // RichError has publics Error() Unwrap() Format()
    17  type RichError struct {
    18  	ErrorChain
    19  }
    20  
    21  var _ error = &RichError{}         // RichError behaves like an error
    22  var _ Wrapper = &RichError{}       // RichError is an error chain
    23  var _ fmt.Formatter = &RichError{} // RichError has features for fmt.Printf
    24  
    25  func newRichError(err error) *RichError {
    26  	return &RichError{*newErrorChain(err)}
    27  }
    28  
    29  // Format provides the fmt.Formatter function
    30  func (e *RichError) Format(s fmt.State, verb rune) {
    31  	if IsValueVerb(verb) {
    32  		if format := PrintfFormat(s); format != DefaultFormat {
    33  			ChainString(e, format)
    34  		}
    35  		io.WriteString(s, e.Error())
    36  	} else if IsStringVerb(verb) {
    37  		io.WriteString(s, e.Error())
    38  	} else if IsQuoteVerb(verb) {
    39  		io.WriteString(s, strconv.Quote(e.Error()))
    40  	}
    41  }
    42  
    43  // IsPlusFlag determines if fmt.State has the '+' flag
    44  func IsPlusFlag(s fmt.State) bool {
    45  	return s.Flag('+')
    46  }
    47  
    48  // IsMinusFlag determines if fmt.State has the '-' flag
    49  func IsMinusFlag(s fmt.State) bool {
    50  	return s.Flag('-')
    51  }
    52  
    53  // IsValueVerb determines if the rune corresponds to the %v value verb
    54  func IsValueVerb(r rune) bool {
    55  	return r == 'v'
    56  }
    57  
    58  // IsStringVerb determines if the rune corresponds to the %s string verb
    59  func IsStringVerb(r rune) bool {
    60  	return r == 's'
    61  }
    62  
    63  // IsQuoteVerb determines if the rune corresponds to the %q quote verb
    64  func IsQuoteVerb(r rune) bool {
    65  	return r == 'q'
    66  }