-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
66 lines (59 loc) · 1.66 KB
/
errors.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package internal
import (
"fmt"
"github.com/invopop/gobl"
"github.com/invopop/gobl/cbc"
)
// Status codes used in the CLI that map to HTTP status codes
const (
StatusBadRequest int = 400
StatusConflict int = 409
StatusUnprocessableEntity int = 422
)
// Error wraps around around any messages generated by the cli and attempts
// to provide a structured output that can be interpreted.
type Error struct {
Code int `json:"code"` // HTTP status code
Key cbc.Key `json:"key,omitempty"` // For GOBL errors
Fields gobl.FieldErrors `json:"fields,omitempty"` // Structured error messages for fields
Message string `json:"message,omitempty"`
}
// Error provides a string representation of the error. This should only really
// be used for testing purposes.
func (e *Error) Error() string {
if e == nil {
return ""
}
msg := e.Message
if msg == "" && e.Fields != nil {
msg = e.Fields.Error()
}
if msg == "" {
msg = e.Key.String()
}
if msg == "" {
msg = "unknown-error"
}
return fmt.Sprintf("code=%d, message=%s", e.Code, msg)
}
// wrapError is used to ensure that we always provide a structured response
func wrapError(code int, err error) *Error {
if e, ok := err.(*Error); ok {
return e
}
out := new(Error)
out.Code = code
switch e := err.(type) {
case *gobl.Error:
out.Key = e.Key()
out.Fields = e.Fields()
out.Message = e.Message()
default:
out.Message = e.Error()
}
return out
}
// wrapErrorf makes it easier to wrap around errors that need extra data.
func wrapErrorf(code int, format string, args ...any) *Error {
return wrapError(code, fmt.Errorf(format, args...))
}