@@ -1977,3 +1977,70 @@ func Benchmark_Ctx_AcquireReleaseFlow(b *testing.B) {
19771977 }
19781978 })
19791979}
1980+
1981+ func TestErrorHandler_PicksRightOne (t * testing.T ) {
1982+ // common handler to be used by all routes,
1983+ // it will always fail by returning an error since
1984+ // we need to test that the right ErrorHandler is invoked
1985+ handler := func (c * Ctx ) error {
1986+ return errors .New ("random error" )
1987+ }
1988+
1989+ // subapp /api/v1/users [no custom error handler]
1990+ appAPIV1Users := New ()
1991+ appAPIV1Users .Get ("/" , handler )
1992+
1993+ // subapp /api/v1/use [with custom error handler]
1994+ appAPIV1UseEH := func (c * Ctx , _ error ) error {
1995+ return c .SendString ("/api/v1/use error handler" )
1996+ }
1997+ appAPIV1Use := New (Config {ErrorHandler : appAPIV1UseEH })
1998+ appAPIV1Use .Get ("/" , handler )
1999+
2000+ // subapp: /api/v1 [with custom error handler]
2001+ appV1EH := func (c * Ctx , _ error ) error {
2002+ return c .SendString ("/api/v1 error handler" )
2003+ }
2004+ appV1 := New (Config {ErrorHandler : appV1EH })
2005+ appV1 .Get ("/" , handler )
2006+ appV1 .Mount ("/users" , appAPIV1Users )
2007+ appV1 .Mount ("/use" , appAPIV1Use )
2008+
2009+ // root app [no custom error handler]
2010+ app := New ()
2011+ app .Get ("/" , handler )
2012+ app .Mount ("/api/v1" , appV1 )
2013+
2014+ testCases := []struct {
2015+ path string // the endpoint url to test
2016+ expected string // the expected error response
2017+ }{
2018+ // /api/v1/users mount doesn't have custom ErrorHandler
2019+ // so it should use the upper-nearest one (/api/v1)
2020+ {"/api/v1/users" , "/api/v1 error handler" },
2021+
2022+ // /api/v1/users mount has a custom ErrorHandler
2023+ {"/api/v1/use" , "/api/v1/use error handler" },
2024+
2025+ // /api/v1 mount has a custom ErrorHandler
2026+ {"/api/v1" , "/api/v1 error handler" },
2027+
2028+ // / mount doesn't have custom ErrorHandler, since is
2029+ // the root path i will use Fiber's default Error Handler
2030+ {"/" , "random error" },
2031+ }
2032+
2033+ for _ , testCase := range testCases {
2034+ resp , err := app .Test (httptest .NewRequest (MethodGet , testCase .path , nil ))
2035+ if err != nil {
2036+ t .Fatal (err )
2037+ }
2038+
2039+ body , err := io .ReadAll (resp .Body )
2040+ if err != nil {
2041+ t .Fatal (err )
2042+ }
2043+
2044+ utils .AssertEqual (t , testCase .expected , string (body ))
2045+ }
2046+ }
0 commit comments