forked from tsuru/tsuru
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrors.go
127 lines (106 loc) · 2.46 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
115
116
117
118
119
120
121
122
123
124
125
126
127
// Copyright 2012 tsuru 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 provides facilities with error handling.
package errors
import (
"fmt"
"strings"
)
// HTTP represents an HTTP error. It implements the error interface.
//
// Each HTTP error has a Code and a message explaining what went wrong.
type HTTP struct {
// Status code.
Code int
// Message explaining what went wrong.
Message string
}
func (e *HTTP) Error() string {
return e.Message
}
func (e *HTTP) StatusCode() int {
return e.Code
}
// ValidationError is an error implementation used whenever a validation
// failure occurs.
type ValidationError struct {
Message string
}
func (err *ValidationError) Error() string {
return err.Message
}
type ConflictError ValidationError
func (err *ConflictError) Error() string {
return err.Message
}
type NotAuthorizedError ValidationError
func (err *NotAuthorizedError) Error() string {
return err.Message
}
type MultiError struct {
errors []error
}
func NewMultiError(errs ...error) *MultiError {
return &MultiError{errors: errs}
}
func (m *MultiError) Add(err error) {
m.errors = append(m.errors, err)
}
func (m *MultiError) Len() int {
return len(m.errors)
}
func (m *MultiError) ToError() error {
if m.Len() == 0 {
return nil
}
if m.Len() == 1 {
return m.errors[0]
}
return m
}
func (m *MultiError) Error() string {
if m.Len() == 0 {
return "multi error created but no errors added"
}
if m.Len() == 1 {
return fmt.Sprintf("%+v", m.errors[0])
}
msg := fmt.Sprintf("multiple errors reported (%d):\n", len(m.errors))
for i, err := range m.errors {
msg += fmt.Sprintf("error #%d: %+v\n", i, err)
}
return msg
}
func (m *MultiError) Format(s fmt.State, verb rune) {
if m.Len() == 0 {
return
}
fmtString := "%"
if s.Flag('+') {
fmtString += "+"
}
if s.Flag('#') {
fmtString += "#"
}
fmtString += string(verb)
if m.Len() == 1 {
fmt.Fprintf(s, fmtString, m.errors[0])
return
}
errors := make([]string, len(m.errors))
for i, err := range m.errors {
errors[i] = fmt.Sprintf("error %d: "+fmtString, i, err)
}
fmt.Fprintf(s, "multiple errors reported (%d): %s", m.Len(), strings.Join(errors, " - "))
}
type CompositeError struct {
Base error
Message string
}
func (err *CompositeError) Error() string {
if err.Base == nil {
return err.Message
}
return fmt.Sprintf("%s Caused by: %s", err.Message, err.Base.Error())
}