github.com/jshiv/can-go@v0.2.1-0.20210224011015-069e90e90bdf/pkg/dbc/error.go (about)

     1  package dbc
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"text/scanner"
     7  )
     8  
     9  // Error represents an error in a DBC file.
    10  type Error interface {
    11  	error
    12  
    13  	// Position of the error in the DBC file.
    14  	Position() scanner.Position
    15  
    16  	// Reason for the error.
    17  	Reason() string
    18  }
    19  
    20  // validationError is an error resulting from an invalid DBC definition.
    21  type validationError struct {
    22  	pos    scanner.Position
    23  	reason string
    24  	cause  error
    25  }
    26  
    27  func (e *validationError) Unwrap() error {
    28  	return e.cause
    29  }
    30  
    31  var _ Error = &validationError{}
    32  
    33  func (e *validationError) Error() string {
    34  	return fmt.Sprintf("%v: %s (validate)", e.Position(), e.reason)
    35  }
    36  
    37  // Reason returns the reason for the error.
    38  func (e *validationError) Reason() string {
    39  	return e.reason
    40  }
    41  
    42  // Position returns the position of the validation error in the DBC file.
    43  //
    44  // When the validation error results from an invalid nested definition, the position of the nested definition is
    45  // returned.
    46  func (e *validationError) Position() scanner.Position {
    47  	var errValidation *validationError
    48  	if errors.As(e.cause, &errValidation) {
    49  		return errValidation.Position()
    50  	}
    51  	return e.pos
    52  }
    53  
    54  // parseError is an error resulting from a failure to parse a DBC file.
    55  type parseError struct {
    56  	pos    scanner.Position
    57  	reason string
    58  }
    59  
    60  var _ Error = &parseError{}
    61  
    62  func (e *parseError) Error() string {
    63  	return fmt.Sprintf("%v: %s (parse)", e.pos, e.reason)
    64  }
    65  
    66  // Reason returns the reason for the error.
    67  func (e *parseError) Reason() string {
    68  	return e.reason
    69  }
    70  
    71  // Position returns the position of the parse error in the DBC file.
    72  func (e *parseError) Position() scanner.Position {
    73  	return e.pos
    74  }