Skip to content

Commit

Permalink
Fix: error handler of app and its sub apps not saved when mounted in …
Browse files Browse the repository at this point in the history
…group (#1649)
  • Loading branch information
ichxxx committed Dec 28, 2021
1 parent 68d3b77 commit 637f0c1
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
24 changes: 24 additions & 0 deletions app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,30 @@ func Test_App_ErrorHandler_RouteStack(t *testing.T) {
utils.AssertEqual(t, "1: USE error", string(body))
}

func Test_App_ErrorHandler_GroupMount(t *testing.T) {
micro := New(Config{
ErrorHandler: func(c *Ctx, err error) error {
utils.AssertEqual(t, "0: GET error", err.Error())
return c.Status(500).SendString("1: custom error")
},
})
micro.Get("/doe", func(c *Ctx) error {
return errors.New("0: GET error")
})

app := New()
v1 := app.Group("/v1")
v1.Mount("/john", micro)

resp, err := app.Test(httptest.NewRequest(MethodGet, "/v1/john/doe", nil))
utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, 500, resp.StatusCode, "Status code")

body, err := ioutil.ReadAll(resp.Body)
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, "1: custom error", string(body))
}

func Test_App_Nested_Params(t *testing.T) {
app := New()

Expand Down
14 changes: 13 additions & 1 deletion group.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package fiber
import (
"fmt"
"reflect"
"strings"
"sync/atomic"
)

Expand All @@ -22,13 +23,24 @@ type Group struct {
// compose them as a single service using Mount.
func (grp *Group) Mount(prefix string, fiber *App) Router {
stack := fiber.Stack()
groupPath := getGroupPath(grp.prefix, prefix)

for m := range stack {
for r := range stack[m] {
route := grp.app.copyRoute(stack[m][r])
grp.app.addRoute(route.Method, grp.app.addPrefixToRoute(getGroupPath(grp.prefix, prefix), route))
grp.app.addRoute(route.Method, grp.app.addPrefixToRoute(groupPath, route))
}
}

// Save the fiber's error handler and its sub apps
groupPath = strings.TrimRight(groupPath, "/")
if fiber.config.ErrorHandler != nil {
grp.app.errorHandlers[groupPath] = fiber.config.ErrorHandler
}
for mountedPrefixes, errHandler := range fiber.errorHandlers {
grp.app.errorHandlers[groupPath+mountedPrefixes] = errHandler
}

atomic.AddUint32(&grp.app.handlerCount, fiber.handlerCount)

return grp
Expand Down

0 comments on commit 637f0c1

Please sign in to comment.