-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
71 lines (53 loc) · 1.75 KB
/
handler.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
// Package airbrake provides Airbrake/Errbit integration.
package airbrake
import (
"github.com/airbrake/gobrake"
"emperror.dev/emperror"
"emperror.dev/emperror/httperr"
"emperror.dev/emperror/utils/keyvals"
)
// Handler is responsible for sending errors to Airbrake/Errbit.
type Handler struct {
notifier *gobrake.Notifier
sendSynchronously bool
}
// New creates a new handler.
func New(projectID int64, projectKey string) *Handler {
return NewFromNotifier(gobrake.NewNotifier(projectID, projectKey))
}
// NewSync creates a new handler that sends errors synchronously.
func NewSync(projectID int64, projectKey string) *Handler {
handler := New(projectID, projectKey)
handler.sendSynchronously = true
return handler
}
// NewFromNotifier creates a new handler from a notifier instance.
func NewFromNotifier(notifier *gobrake.Notifier) *Handler {
handler := &Handler{
notifier: notifier,
}
return handler
}
// NewSyncFromNotifier creates a new handler from a notifier instance that sends errors synchronously.
func NewSyncFromNotifier(notifier *gobrake.Notifier) *Handler {
handler := NewFromNotifier(notifier)
handler.sendSynchronously = true
return handler
}
// Handle sends the error to Airbrake/Errbit.
func (h *Handler) Handle(err error) {
// Get HTTP request (if any)
req, _ := httperr.HTTPRequest(err)
notice := h.notifier.Notice(emperror.ExposeStackTrace(err), req, 1)
// Extract context from the error and attach it to the notice
notice.Params = keyvals.ToMap(emperror.Context(err))
if h.sendSynchronously {
_, _ = h.notifier.SendNotice(notice)
} else {
h.notifier.SendNoticeAsync(notice)
}
}
// Close closes the underlying notifier and waits for asynchronous reports to finish.
func (h *Handler) Close() error {
return h.notifier.Close()
}