...

Source file src/github.com/goph/emperror/handler/airbrakehandler/handler.go

Documentation: github.com/goph/emperror/handler/airbrakehandler

     1  // Package airbrakehandler provides Airbrake/Errbit integration.
     2  package airbrakehandler
     3  
     4  import (
     5  	"github.com/airbrake/gobrake"
     6  
     7  	"github.com/goph/emperror"
     8  	"github.com/goph/emperror/httperr"
     9  	"github.com/goph/emperror/internal/keyvals"
    10  )
    11  
    12  // Handler is responsible for sending errors to Airbrake/Errbit.
    13  type Handler struct {
    14  	notifier *gobrake.Notifier
    15  
    16  	sendSynchronously bool
    17  }
    18  
    19  // New creates a new handler.
    20  func New(projectID int64, projectKey string) *Handler {
    21  	return NewFromNotifier(gobrake.NewNotifier(projectID, projectKey))
    22  }
    23  
    24  // NewSync creates a new handler that sends errors synchronously.
    25  func NewSync(projectID int64, projectKey string) *Handler {
    26  	handler := New(projectID, projectKey)
    27  
    28  	handler.sendSynchronously = true
    29  
    30  	return handler
    31  }
    32  
    33  // NewFromNotifier creates a new handler from a notifier instance.
    34  func NewFromNotifier(notifier *gobrake.Notifier) *Handler {
    35  	handler := &Handler{
    36  		notifier: notifier,
    37  	}
    38  
    39  	return handler
    40  }
    41  
    42  // NewSyncFromNotifier creates a new handler from a notifier instance that sends errors synchronously.
    43  func NewSyncFromNotifier(notifier *gobrake.Notifier) *Handler {
    44  	handler := NewFromNotifier(notifier)
    45  
    46  	handler.sendSynchronously = true
    47  
    48  	return handler
    49  }
    50  
    51  // Handle sends the error to Airbrake/Errbit.
    52  func (h *Handler) Handle(err error) {
    53  	// Get HTTP request (if any)
    54  	req, _ := httperr.HTTPRequest(err)
    55  
    56  	notice := h.notifier.Notice(emperror.ExposeStackTrace(err), req, 1)
    57  
    58  	// Extract context from the error and attach it to the notice
    59  	notice.Params = keyvals.ToMap(emperror.Context(err))
    60  
    61  	if h.sendSynchronously {
    62  		_, _ = h.notifier.SendNotice(notice)
    63  	} else {
    64  		h.notifier.SendNoticeAsync(notice)
    65  	}
    66  }
    67  
    68  // Close closes the underlying notifier and waits for asynchronous reports to finish.
    69  func (h *Handler) Close() error {
    70  	return h.notifier.Close()
    71  }
    72  

View as plain text