-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
error.go
64 lines (55 loc) · 1.59 KB
/
error.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
package herodot
import (
"net/http"
"github.com/Sirupsen/logrus"
"github.com/ory-am/fosite"
"github.com/pkg/errors"
"reflect"
)
type Error struct {
OriginalError error `json:"-"`
StatusCode int `json:"code"`
Description string `json:"description,omitempty"`
Name string `json:"name"`
}
func (e Error) Error() string {
return e.OriginalError.Error()
}
type stackTracer interface {
StackTrace() errors.StackTrace
}
type causer interface {
Cause() error
}
func ToError(err error) *Error {
if e, ok := err.(*Error); ok {
return e
} else if e, ok := err.(causer); ok {
// causer must be at end of logical loop or fosite error detection wont work
return ToError(e.Cause())
} else if rfcErr := fosite.ErrorToRFC6749Error(err); rfcErr.Name != fosite.UnknownErrorName {
return &Error{
OriginalError: err,
StatusCode: rfcErr.StatusCode,
Description: rfcErr.Description,
Name: rfcErr.Name,
}
}
return &Error{
OriginalError: err,
Name: "internal-error",
StatusCode: http.StatusInternalServerError,
}
}
func LogError(err error, id string, code int) {
logrus.WithError(err).WithField("request_id", id).WithField("status", code).Errorln("An error occurred")
if e, ok := err.(stackTracer); ok {
logrus.Debugf("Stack trace: %+v", e.StackTrace())
} else if e, ok := errors.Cause(err).(stackTracer); ok {
logrus.Debugf("Stack trace: %+v", e.StackTrace())
} else if e, ok := err.(*Error); ok {
LogError(e.OriginalError, id, code)
} else {
logrus.Debugf("Stack trace could not be recovered from error type %s", reflect.TypeOf(err))
}
}