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

     1  package spiceerrors
     2  
     3  import "time"
     4  
     5  // TerminationError represents an error that captures contextual information to make
     6  // available on process termination. The error will be marshalled as JSON and
     7  // serialized into a file-path specified via CLI arguments
     8  type TerminationError struct {
     9  	error
    10  	Component   string            `json:"component"`
    11  	Timestamp   time.Time         `json:"timestamp"`
    12  	ErrorString string            `json:"error"`
    13  	Metadata    map[string]string `json:"metadata"`
    14  	exitCode    int
    15  }
    16  
    17  // ExitCode returns the exit code to be returned on process termination
    18  func (e TerminationError) ExitCode() int {
    19  	return e.exitCode
    20  }
    21  
    22  // ErrorBuilder is a fluent-style builder for TerminationError
    23  type ErrorBuilder struct {
    24  	terminationErr TerminationError
    25  }
    26  
    27  // TerminationError returns the built termination TerminationError
    28  func (eb *ErrorBuilder) Error() TerminationError {
    29  	return eb.terminationErr
    30  }
    31  
    32  // Component specifies the component in SpiceDB that
    33  func (eb *ErrorBuilder) Component(component string) *ErrorBuilder {
    34  	eb.terminationErr.Component = component
    35  	return eb
    36  }
    37  
    38  // Metadata adds a new key-value pair of metadata to the termination TerminationError being built
    39  func (eb *ErrorBuilder) Metadata(key, value string) *ErrorBuilder {
    40  	eb.terminationErr.Metadata[key] = value
    41  	return eb
    42  }
    43  
    44  // ExitCode defines the ExitCode to be used upon process termination. Defaults to 1 if not specified.
    45  func (eb *ErrorBuilder) ExitCode(exitCode int) *ErrorBuilder {
    46  	eb.terminationErr.exitCode = exitCode
    47  	return eb
    48  }
    49  
    50  // Timestamp defines the time of the error. Defaults to time.Now().UTC() if not specified.
    51  func (eb *ErrorBuilder) Timestamp(timestamp time.Time) *ErrorBuilder {
    52  	eb.terminationErr.Timestamp = timestamp
    53  	return eb
    54  }
    55  
    56  // NewTerminationErrorBuilder returns a new ErrorBuilder for a termination.TerminationError.
    57  func NewTerminationErrorBuilder(err error) *ErrorBuilder {
    58  	return &ErrorBuilder{terminationErr: TerminationError{
    59  		error:       err,
    60  		Component:   "unspecified",
    61  		Timestamp:   time.Now().UTC(),
    62  		ErrorString: err.Error(),
    63  		Metadata:    make(map[string]string, 0),
    64  		exitCode:    1,
    65  	}}
    66  }