github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/module/irrecoverable/exception.go (about)

     1  package irrecoverable
     2  
     3  import (
     4  	"fmt"
     5  )
     6  
     7  // exception represents an unexpected error. An unexpected error is any error returned
     8  // by a function, other than the error specifically documented as expected in that
     9  // function's interface.
    10  //
    11  // It wraps an error, which could be a sentinel error. IT does NOT IMPLEMENT an UNWRAP method,
    12  // so the enclosed error's type cannot be accessed. Therefore, methods such as `errors.As` and
    13  // `errors.Is` do not detect the exception as any known sentinel error.
    14  // NOTE: this type is private, because checking for an exception (as opposed to checking for the
    15  // set of expected error types) is considered an anti-pattern because it may miss unexpected
    16  // errors which are not implemented as an exception.
    17  //
    18  // Functions may return an exception when:
    19  //   - they are interpreting any error returning from a 3rd party module as unexpected
    20  //   - they are reacting to an unexpected condition internal to their stack frame and returning a generic error
    21  //
    22  // Functions must return an exception when:
    23  //   - they are interpreting any documented sentinel error returned from a flow-go module as unexpected
    24  type exception struct {
    25  	err error
    26  }
    27  
    28  // Error returns the error string of the exception. It is always prefixed by `[exception!]`
    29  // to easily differentiate unexpected errors in logs.
    30  func (e exception) Error() string {
    31  	return "[exception!] " + e.err.Error()
    32  }
    33  
    34  // NewException wraps the input error as an exception, stripping any sentinel error information.
    35  // This ensures that all upper levels in the stack will consider this an unexpected error.
    36  func NewException(err error) error {
    37  	return exception{err: err}
    38  }
    39  
    40  // NewExceptionf is NewException with the ability to add formatting and context to the error text.
    41  func NewExceptionf(msg string, args ...any) error {
    42  	return NewException(fmt.Errorf(msg, args...))
    43  }