Skip to content

Conversation

@majiayu000
Copy link

Fixes #2485

Changes

  • Store RouteNotFound handler for "/*" path on Echo instance for fallback use
  • Modify group middleware to check for root RouteNotFound handler before using default
  • Add tests verifying root 404 handler fallback behavior for groups with middleware

…iddleware

When a group has middleware, the RouteNotFound handler registered at the
root level is now properly used as a fallback. Previously, groups with
middleware would always use the default NotFoundHandler instead of
falling back to the root's custom RouteNotFound handler.

This fix:
- Adds a routeNotFoundHandler field to Echo to store the root handler
- Modifies group.Use() to use a fallback handler that checks for the
  root's RouteNotFound handler at request time
- Updates tests to reflect the new expected behavior

Fixes labstack#2485

Signed-off-by: majiayu000 <[email protected]>
@aldas
Copy link
Contributor

aldas commented Jan 1, 2026

Hi, happy new year!

This is interesting idea but I think you can achieve same by replacing default NotFoundHandler (assuming you do not deal with multiple echo instances which routes/groups are added in mixed order)

	echo.NotFoundHandler = func(c echo.Context) error {
		return echo.NewHTTPError(http.StatusNotFound, "custom route not found")
	}
	e.RouteNotFound("*", echo.NotFoundHandler)

	g := e.Group("/group") // <--- will use replaced echo.NotFoundHandler 

the root problem/cause here is that we have these 404 handlers added.

echo/group.go

Lines 27 to 33 in d0f9d1e

// group level middlewares are different from Echo `Pre` and `Use` middlewares (those are global). Group level middlewares
// are only executed if they are added to the Router with route.
// So we register catch all route (404 is a safe way to emulate route match) for this group and now during routing the
// Router would find route to match our request path and therefore guarantee the middleware(s) will get executed.
g.RouteNotFound("", NotFoundHandler)
g.RouteNotFound("/*", NotFoundHandler)
}

Which is something we can not change but if we are looking for workaround I think replacing the 404handler is probably the easiest way.

@aldas
Copy link
Contributor

aldas commented Jan 1, 2026

also these group level 404 routes can be replaced

	my404 := func(c echo.Context) error {
		return echo.NewHTTPError(http.StatusNotFound, "custom route not found")
	}
	g := e.Group("/group")
	g.RouteNotFound("", my404)
	g.RouteNotFound("/*", my404)
	
	echo.NotFoundHandler = my404
	e.RouteNotFound("*", my404)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RouteNotFound handler does not falls back to root one

2 participants