Group.Use() silently replaces an explicitly registered group RouteNotFound handler
Group.Use auto-registers implicit RouteNotFound routes at "" and "/*" with allowOverwrite: true (group.go), so group middleware also runs for unmatched paths. If a custom 404 handler was registered for the group before the first Use call, the implicit registration overwrites it and requests get Echo's default 404 instead. The reverse order (Use first, then RouteNotFound) works, so behavior depends on registration order.
Repro:
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/labstack/echo/v5"
)
func main() {
e := echo.New()
g := e.Group("/v1")
// Explicit custom 404 handler for everything under /v1
g.RouteNotFound("/*", func(c *echo.Context) error {
return c.String(http.StatusNotFound, "custom group 404")
})
// Adding group middleware afterwards silently replaces the custom 404 handler
g.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error { return next(c) }
})
req := httptest.NewRequest(http.MethodGet, "/v1/nonexistent", nil)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
fmt.Printf("after Use(): status=%d body=%q\n", rec.Code, rec.Body.String())
// got: status=404 body="{\"message\":\"Not Found\"}\n" (echo's default 404)
// want: status=404 body="custom group 404"
// Sanity check: registering the custom 404 AFTER Use() works.
e2 := echo.New()
g2 := e2.Group("/v1")
g2.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error { return next(c) }
})
g2.RouteNotFound("/*", func(c *echo.Context) error {
return c.String(http.StatusNotFound, "custom group 404")
})
req2 := httptest.NewRequest(http.MethodGet, "/v1/nonexistent", nil)
rec2 := httptest.NewRecorder()
e2.ServeHTTP(rec2, req2)
fmt.Printf("reverse order: status=%d body=%q\n", rec2.Code, rec2.Body.String())
}
Actual: 404 {"message":"Not Found"} Expected: 404 "custom group 404"
Echo v5 master @ 99c395d, Go 1.26.6.
I used AI tools to find and reproduce this; I reviewed it myself.
Thanks for the report. This ordering is how group 404s currently work. When a group has middleware, Group.Use registers catch-all RouteNotFound routes so that the middleware also runs for unmatched paths. A custom handler registered after Use replaces them (#2411, TestGroup_RouteNotFoundWithMiddleware). Register the group's RouteNotFound after Use, or pass the middleware to e.Group(prefix, m...). We'll make the ordering explicit in the doc comments. Closing as working as intended.