github.com/DelineaXPM/dsv-cli@v1.40.6/errors/errors.go (about)

     1  package errors
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"strings"
     7  )
     8  
     9  // ApiError is an improved error class.
    10  type ApiError struct {
    11  	stack        []string
    12  	httpResponse *http.Response
    13  }
    14  
    15  // New creates a new error from an error.
    16  func New(err error) *ApiError {
    17  	if err == nil {
    18  		return nil
    19  	}
    20  	return NewS(err.Error())
    21  }
    22  
    23  // NewF creates a new formatted error.
    24  func NewF(format string, a ...interface{}) *ApiError {
    25  	if format == "" {
    26  		return nil
    27  	}
    28  	return NewS(fmt.Sprintf(format, a...))
    29  }
    30  
    31  // NewS creates a new error from a string.
    32  func NewS(msg string) *ApiError {
    33  	if msg == "" {
    34  		return nil
    35  	}
    36  	return &ApiError{
    37  		stack: []string{strings.TrimSpace(msg)},
    38  	}
    39  }
    40  
    41  func (e *ApiError) Error() string {
    42  	return e.String()
    43  }
    44  
    45  func (e *ApiError) String() string {
    46  	if e == nil {
    47  		return ""
    48  	}
    49  	return strings.Join(e.stack, "\n")
    50  }
    51  
    52  func (e *ApiError) WithResponse(httpResponse *http.Response) *ApiError {
    53  	e.httpResponse = httpResponse
    54  	return e
    55  }
    56  
    57  func (e *ApiError) HttpResponse() *http.Response {
    58  	return e.httpResponse
    59  }
    60  
    61  // Grow adds to an error and returns it.
    62  func (e *ApiError) Grow(msg string) *ApiError {
    63  	if e == nil {
    64  		return nil
    65  	}
    66  	if msg == "" {
    67  		return e
    68  	}
    69  	e.stack = append([]string{msg}, e.stack...)
    70  	return e
    71  }
    72  
    73  // Or coalesces two errors.
    74  func (e *ApiError) Or(f *ApiError) *ApiError {
    75  	if e == nil || e.stack == nil || len(e.stack) < 1 {
    76  		return f
    77  	}
    78  	return e
    79  }
    80  
    81  // And ands two errors.
    82  func (e *ApiError) And(f *ApiError) *ApiError {
    83  	if f == nil || f.stack == nil || len(f.stack) < 1 {
    84  		return e
    85  	}
    86  	if e == nil || e.stack == nil || len(e.stack) < 1 {
    87  		return f
    88  	}
    89  	e.stack = append(e.stack, "and")
    90  	e.stack = append(e.stack, f.stack...)
    91  	return e
    92  }
    93  
    94  // Convert data and a std err to an api err.
    95  func Convert(data []byte, err error) ([]byte, *ApiError) {
    96  	return data, New(err)
    97  }