Skip to content

Commit

Permalink
contrib/gofiber/fiber.v2: capture error from fiber handler
Browse files Browse the repository at this point in the history
The error returned from the fiber handler was being ignored
by the middleware. It now correctly captures the error and
sets it on the span.

Fixes DataDog#978
  • Loading branch information
dubonzi committed Aug 21, 2021
1 parent d326bfb commit 57af39d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
4 changes: 3 additions & 1 deletion contrib/gofiber/fiber.v2/fiber.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ func Middleware(opts ...Option) func(c *fiber.Ctx) error {
}
span.SetTag(ext.HTTPCode, strconv.Itoa(status))

if cfg.isStatusError(status) {
if err != nil {
span.SetTag(ext.Error, err)
} else if cfg.isStatusError(status) {
// mark 5xx server error
span.SetTag(ext.Error, fmt.Errorf("%d: %s", status, http.StatusText(status)))
}
Expand Down
32 changes: 31 additions & 1 deletion contrib/gofiber/fiber.v2/fiber_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func TestTrace200(t *testing.T) {
})
}

func TestError(t *testing.T) {
func TestStatusError(t *testing.T) {
assert := assert.New(t)
mt := mocktracer.Start()
defer mt.Stop()
Expand Down Expand Up @@ -128,6 +128,36 @@ func TestError(t *testing.T) {
assert.Equal(wantErr, span.Tag(ext.Error).(error).Error())
}

func TestCustomError(t *testing.T) {
assert := assert.New(t)
mt := mocktracer.Start()
defer mt.Stop()

router := fiber.New()
router.Use(Middleware(WithServiceName("foobar")))

router.Get("/err", func(c *fiber.Ctx) error {
c.SendStatus(400)
return fiber.ErrBadRequest
})
r := httptest.NewRequest("GET", "/err", nil)

response, err := router.Test(r, 100)
assert.Equal(nil, err)
assert.Equal(response.StatusCode, 400)

spans := mt.FinishedSpans()
assert.Len(spans, 1)
if len(spans) < 1 {
t.Fatalf("no spans")
}
span := spans[0]
assert.Equal("http.request", span.OperationName())
assert.Equal("foobar", span.Tag(ext.ServiceName))
assert.Equal("400", span.Tag(ext.HTTPCode))
assert.Equal(fiber.ErrBadRequest, span.Tag(ext.Error).(*fiber.Error))
}

func TestGetSpanNotInstrumented(t *testing.T) {
assert := assert.New(t)
router := fiber.New()
Expand Down

0 comments on commit 57af39d

Please sign in to comment.