github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/pkg/spiceerrors/common.go (about)

     1  package spiceerrors
     2  
     3  import "errors"
     4  
     5  // SourcePosition is a position in the input source.
     6  type SourcePosition struct {
     7  	// LineNumber is the 1-indexed line number in the input source.
     8  	LineNumber int
     9  
    10  	// ColumnPosition is the 1-indexed column position in the input source.
    11  	ColumnPosition int
    12  }
    13  
    14  // ErrorWithSource is an error that includes the source text and position
    15  // information.
    16  type ErrorWithSource struct {
    17  	error
    18  
    19  	// SourceCodeString is the input source code string for the error.
    20  	SourceCodeString string
    21  
    22  	// LineNumber is the (1-indexed) line number of the error, or 0 if unknown.
    23  	LineNumber uint64
    24  
    25  	// ColumnPosition is the (1-indexed) column position of the error, or 0 if
    26  	// unknown.
    27  	ColumnPosition uint64
    28  }
    29  
    30  // HasMetadata indicates that the error has metadata defined.
    31  type HasMetadata interface {
    32  	// DetailsMetadata returns the metadata for details for this error.
    33  	DetailsMetadata() map[string]string
    34  }
    35  
    36  // Unwrap returns the inner, wrapped error.
    37  func (err *ErrorWithSource) Unwrap() error {
    38  	return err.error
    39  }
    40  
    41  // NewErrorWithSource creates and returns a new ErrorWithSource.
    42  func NewErrorWithSource(err error, sourceCodeString string, oneIndexedLineNumber uint64, oneIndexedColumnPosition uint64) *ErrorWithSource {
    43  	return &ErrorWithSource{err, sourceCodeString, oneIndexedLineNumber, oneIndexedColumnPosition}
    44  }
    45  
    46  // AsErrorWithSource returns the error as an ErrorWithSource, if applicable.
    47  func AsErrorWithSource(err error) (*ErrorWithSource, bool) {
    48  	var serr *ErrorWithSource
    49  	if errors.As(err, &serr) {
    50  		return serr, true
    51  	}
    52  	return nil, false
    53  }