-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
114 lines (101 loc) · 2.43 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// Copyright 2020 The Verbis Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package errors
import (
"bytes"
"errors"
"fmt"
)
// Application error codes.
const (
CONFLICT = "conflict" // Action cannot be performed
INTERNAL = "config" // Internal error
INVALID = "invalid" // Validation failed
NOTFOUND = "not_found" // Entity does not exist
TEMPLATE = "template" // Templating error
)
// Global Error message when no message has been found.
const GlobalError = "An error has occurred."
// Error defines a standard application error.
type Error struct {
Code string `json:"code"`
Message string `json:"message"`
Operation string `json:"operation"`
Err error `json:"error"`
}
// Error
//
// Returns the string representation of the error message.
func (e *Error) Error() string {
var buf bytes.Buffer
// Print the current operation in our stack, if any.
if e.Operation != "" {
fmt.Fprintf(&buf, "%s: ", e.Operation)
}
// If wrapping an error, print its Error() message.
// Otherwise print the error code & message.
if e.Err != nil {
buf.WriteString(e.Err.Error())
} else {
if e.Code != "" {
_, _ = fmt.Fprintf(&buf, "<%s> ", e.Code)
}
buf.WriteString(e.Message)
}
return buf.String()
}
// Code
//
// Returns the code of the root error, if available.
// Otherwise returns INTERNAL.
func Code(err error) string {
if err == nil {
return ""
} else if e, ok := err.(*Error); ok && e.Code != "" {
return e.Code
} else if ok && e.Err != nil {
return Code(e.Err)
}
return INTERNAL
}
// Message
//
// Returns the human-readable message of the error, if
// available. Otherwise returns a generic error
// message.
func Message(err error) string {
if err == nil {
return ""
} else if e, ok := err.(*Error); ok && e.Message != "" {
return e.Message
} else if ok && e.Err != nil {
return Message(e.Err)
}
fmt.Println(err.Error())
return GlobalError
}
// ToError
//
// Returns a Verbis error from input. If The type is
// not of type Error, nil will be returned.
func ToError(err interface{}) *Error {
switch v := err.(type) {
case *Error:
return v
case Error:
return &v
case error:
return &Error{Err: fmt.Errorf(v.Error())}
case string:
return &Error{Err: fmt.Errorf(v)}
default:
return nil
}
}
// New
//
// Is a wrapper for the stdlib new function.
func New(text string) error {
return errors.New(text)
}