Add support for error (panic) reporting through Sentry
This commit is contained in:
@@ -73,7 +73,6 @@ func LogResponse(next http.Handler) http.Handler {
|
||||
}()
|
||||
|
||||
next.ServeHTTP(wrapped, req)
|
||||
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
+31
-7
@@ -2,23 +2,47 @@ package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/go-chi/chi/middleware"
|
||||
"go.uber.org/zap"
|
||||
|
||||
sentryhttp "github.com/getsentry/sentry-go/http"
|
||||
)
|
||||
|
||||
func Base() []func(http.Handler) http.Handler {
|
||||
func Base(log *zap.Logger) []func(http.Handler) http.Handler {
|
||||
return []func(http.Handler) http.Handler{
|
||||
handleCORS,
|
||||
middleware.RealIP,
|
||||
middleware.RequestID,
|
||||
contextLogger(log),
|
||||
}
|
||||
}
|
||||
|
||||
func Logging(log *zap.Logger) []func(http.Handler) http.Handler {
|
||||
return []func(http.Handler) http.Handler{
|
||||
contextLogger(log),
|
||||
LogRequest,
|
||||
LogResponse,
|
||||
}
|
||||
func Sentry() func(http.Handler) http.Handler {
|
||||
return sentryhttp.New(sentryhttp.Options{
|
||||
Repanic: true,
|
||||
}).Handle
|
||||
}
|
||||
|
||||
// HandlePanic sends 500 error when panic occurs inside the request call
|
||||
func HandlePanic(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
w.WriteHeader(500)
|
||||
|
||||
if _, has := os.LookupEnv("DEBUG_DUMP_STACK_IN_RESPONSE"); has {
|
||||
// Provide nice call stack on endpoint when
|
||||
// we crash
|
||||
w.Write(debug.Stack())
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
}()
|
||||
|
||||
next.ServeHTTP(w, req)
|
||||
})
|
||||
}
|
||||
|
||||
+19
-3
@@ -86,12 +86,28 @@ func (s Server) Serve(ctx context.Context) {
|
||||
|
||||
router := chi.NewRouter()
|
||||
|
||||
router.Use(Base()...)
|
||||
// Base middleware, CORS, RealIP, RequestID, context-logger
|
||||
router.Use(Base(s.log)...)
|
||||
|
||||
if s.httpOpt.Logging {
|
||||
router.Use(Logging(s.log)...)
|
||||
// Logging request if enabled
|
||||
if s.httpOpt.LogRequest {
|
||||
router.Use(LogRequest)
|
||||
}
|
||||
|
||||
// Logging response if enabled
|
||||
if s.httpOpt.LogResponse {
|
||||
router.Use(LogResponse)
|
||||
}
|
||||
|
||||
// Handle panic (sets 500 Server error headers)
|
||||
router.Use(HandlePanic)
|
||||
|
||||
// Reports error to Sentry if enabled
|
||||
if s.httpOpt.EnablePanicReporting {
|
||||
router.Use(Sentry())
|
||||
}
|
||||
|
||||
// Metrics tracking middleware
|
||||
if s.httpOpt.EnableMetrics {
|
||||
router.Use(Middleware(s.httpOpt.MetricsServiceLabel))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user