Skip to content

Commit

Permalink
Improve mux errors (plgd-dev#495)
Browse files Browse the repository at this point in the history
* A bad pattern for a handler is a developer error that can often break whole applications. Panic is more appropriate than just silently logging.

* Allow user to overwrite mux error handler

* Add a warning to HandleFunc about the panic
  • Loading branch information
HRogge committed Oct 26, 2023
1 parent ce94bd9 commit 4d683ce
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion mux/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,13 @@ func NewRouter() *Router {
return router
}

// SetErrorHandler sets a custom error handler for the default mux handler set in the constructor.
func (r *Router) SetErrorHandler(h func(error)) {
r.m.Lock()
defer r.m.Unlock()
r.errors = h
}

// Does path match pattern?
func pathMatch(pattern Route, path string) bool {
return pattern.regexMatcher.regexp.MatchString(path)
Expand Down Expand Up @@ -148,9 +155,11 @@ func (r *Router) DefaultHandle(handler Handler) {
}

// HandleFunc adds a handler function to the Router for pattern.
// This function will panic if the pattern parameter is invalid. If the APP provides 'user defined patterns' better
// use Handle(), which will return an error.
func (r *Router) HandleFunc(pattern string, handler func(w ResponseWriter, r *Message)) {
if err := r.Handle(pattern, HandlerFunc(handler)); err != nil {
r.errors(fmt.Errorf("cannot handle pattern(%v): %w", pattern, err))
panic(fmt.Errorf("cannot handle pattern(%v): %w", pattern, err))
}
}

Expand Down

0 comments on commit 4d683ce

Please sign in to comment.