Skip to content

Commit e151b4b

Browse files
committed
🚨 Test: ErrorHandler selection
1 parent 24ea5f8 commit e151b4b

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

app_test.go

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2761,3 +2761,74 @@ func Benchmark_Ctx_AcquireReleaseFlow(b *testing.B) {
27612761
}
27622762
})
27632763
}
2764+
2765+
func TestErrorHandler_PicksRightOne(t *testing.T) {
2766+
t.Parallel()
2767+
// common handler to be used by all routes,
2768+
// it will always fail by returning an error since
2769+
// we need to test that the right ErrorHandler is invoked
2770+
handler := func(_ Ctx) error {
2771+
return errors.New("random error")
2772+
}
2773+
2774+
// subapp /api/v1/users [no custom error handler]
2775+
appAPIV1Users := New()
2776+
appAPIV1Users.Get("/", handler)
2777+
2778+
// subapp /api/v1/use [with custom error handler]
2779+
appAPIV1UseEH := func(c Ctx, _ error) error {
2780+
return c.SendString("/api/v1/use error handler")
2781+
}
2782+
appAPIV1Use := New(Config{ErrorHandler: appAPIV1UseEH})
2783+
appAPIV1Use.Get("/", handler)
2784+
2785+
// subapp: /api/v1 [with custom error handler]
2786+
appV1EH := func(c Ctx, _ error) error {
2787+
return c.SendString("/api/v1 error handler")
2788+
}
2789+
appV1 := New(Config{ErrorHandler: appV1EH})
2790+
appV1.Get("/", handler)
2791+
appV1.Use("/users", appAPIV1Users)
2792+
appV1.Use("/use", appAPIV1Use)
2793+
2794+
// root app [no custom error handler]
2795+
app := New()
2796+
app.Get("/", handler)
2797+
app.Use("/api/v1", appV1)
2798+
2799+
testCases := []struct {
2800+
path string // the endpoint url to test
2801+
expected string // the expected error response
2802+
}{
2803+
// /api/v1/users mount doesn't have custom ErrorHandler
2804+
// so it should use the upper-nearest one (/api/v1)
2805+
{"/api/v1/users", "/api/v1 error handler"},
2806+
2807+
// /api/v1/use mount has a custom ErrorHandler
2808+
{"/api/v1/use", "/api/v1/use error handler"},
2809+
2810+
// /api/v1 mount has a custom ErrorHandler
2811+
{"/api/v1", "/api/v1 error handler"},
2812+
2813+
// / mount doesn't have custom ErrorHandler, since is
2814+
// the root path i will use Fiber's default Error Handler
2815+
{"/", "random error"},
2816+
}
2817+
2818+
for _, testCase := range testCases {
2819+
t.Run(testCase.path, func(t *testing.T) {
2820+
t.Parallel()
2821+
resp, err := app.Test(httptest.NewRequest(MethodGet, testCase.path, http.NoBody))
2822+
if err != nil {
2823+
t.Fatal(err)
2824+
}
2825+
2826+
body, err := io.ReadAll(resp.Body)
2827+
if err != nil {
2828+
t.Fatal(err)
2829+
}
2830+
2831+
require.Equal(t, testCase.expected, string(body))
2832+
})
2833+
}
2834+
}

0 commit comments

Comments
 (0)