To trace Twirp errors in Datadog instead of generic HTTP errors, you can create a custom middleware for your Twirp service that wraps around the Datadog-provided HTTP middleware. This custom middleware will handle the conversion from Twirp errors to the format that Datadog understands.
Here's an example of how you might write such a middleware in Go:
package main
import (
"context"
"net/http"
"strconv"
"github.com/twitchtv/twirp"
twirptrace "github.com/twitchtv/twirp/hooks/trace"
ddtrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/net/http"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
)
// wrapDatadogMiddleware creates a new HTTP middleware that captures the Twirp errors for Datadog
func wrapDatadogMiddleware(base http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Start a new Datadog span
span, ctx := tracer.StartSpanFromContext(r.Context(), "twirp.request")
defer span.Finish()
// Attach the span to the context
r = r.WithContext(ctx)
// Use a ResponseWriter wrapper to capture the status code
ww := &responseWriterWrapper{ResponseWriter: w}
// Serve the request using the base handler (Datadog's middleware)
base.ServeHTTP(ww, r)
// Check if a Twirp error was set in the context
twerr, ok := twirp.ErrorFromContext(ctx)
if ok {
// Record the Twirp error as the error for the span
span.SetTag("twirp.error_code", twerr.Code())
span.SetTag("twirp.error_msg", twerr.Msg())
span.SetTag("error", true)
// Set the status code if it's not already set by the base handler
if ww.statusCode == 0 {
ww.WriteHeader(mapTwirpCodeToHTTPStatus(twerr.Code()))
}
}
// Set the status code tag for the Datadog span
span.SetTag("http.status_code", strconv.Itoa(ww.statusCode))
})
}
// mapTwirpCodeToHTTPStatus maps Twirp error codes to the corresponding HTTP status codes
func mapTwirpCodeToHTTPStatus(code twirp.ErrorCode) int {
switch code {
case twirp.Canceled:
return http.StatusRequestTimeout
case twirp.Unknown:
return http.StatusInternalServerError
case twirp.InvalidArgument:
return http.StatusBadRequest
case twirp.DeadlineExceeded:
return http.StatusGatewayTimeout
case twirp.NotFound:
return http.StatusNotFound
case twirp.BadRoute:
return http.StatusNotFound
case twirp.AlreadyExists:
return http.StatusConflict
case twirp.PermissionDenied:
return http.StatusForbidden
case twirp.ResourceExhausted:
return http.StatusTooManyRequests
case twirp.FailedPrecondition:
return http.StatusPreconditionFailed
case twirp.Aborted:
return http.StatusConflict
case twirp.OutOfRange:
return http.StatusBadRequest
case twirp.Unimplemented:
return http.StatusNotImplemented
case twirp.Internal:
return http.StatusInternalServerError
case twirp.Unavailable:
return http.StatusServiceUnavailable
case twirp.DataLoss:
return http.StatusInternalServerError
case twirp.Unauthenticated:
return http.StatusUnauthorized
default:
return http.StatusInternalServerError
}
}
// responseWriterWrapper is a wrapper around http.ResponseWriter that allows us to capture the status code
type responseWriterWrapper struct {
http.ResponseWriter
statusCode int
}
func (w *responseWriterWrapper) WriteHeader(code int) {
w.statusCode = code
w.ResponseWriter.WriteHeader(code)
}
func main() {
// Initialize your Twirp service and Datadog tracer here...
// Wrap the Twirp service with the Datadog HTTP middleware
ddMiddleware := ddtrace.WrapHandler(yourTwirpService)
// Wrap the Datadog HTTP middleware with your custom middleware
customMiddleware := wrapDatadogMiddleware(ddMiddleware)
// Use your custom middleware as the handler for HTTP requests
http.Handle(twirpServicePath, customMiddleware)
// Start your server...
}
In this code snippet, we create a custom middleware function, wrapDatadogMiddleware, that wraps around your Twirp service already instrumented with Datadog's HTTP middleware. It captures Twirp errors and converts them to Datadog spans, setting appropriate tags based on the Twirp error details.
You'll need to replace `yourTwirpService