Best practices for handling errors in chain of custom modules

1. The problem I’m having:

I’m trying to understand what is the best practices to handle errors in a chain of modules that run inside route block.

If I want that once I get an error in my custom module, the chain will stop and not continue to the next module, should I return nil? or maybe the error itself and then use handle_errors block: handle_errors (Caddyfile directive) — Caddy Documentation?

What happen if I return nil but still write the bytes to the ResponseWriter?
Does caddy recognize it as no error? (from what I checked, that’s what happen).

This is an example for how I stop the chain for now:

func (m Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
       err := ..
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return nil
	} else {
          next.ServeHTTP(w, r)
       }

Is this how Caddy expect to stop the chain and handler errors?

Thanks!

2. Error messages and/or full log output:

No error message, because it's a best practices question

3. Caddy version:

v2.8.4

4. How I installed and ran Caddy:

a. System environment:

golang:1.23-alpine docker image inside kubernetes

b. Command:

caddy run --config /etc/caddy/Caddyfile

c. Service/unit/compose file:

d. My complete Caddy config:

:2022 {
  route /* {
    custom_module_a
    custom_module_b
  }
}

5. Links to relevant resources:

Hi,
Someone can recommend what are the best practices in such case?

It’s best to return a HandlerError with the preferred status code and message, otherwise Caddy will only return 500 to the client.

Then, Caddy doesn’t consider it an error rather a successful handling.

Correct

If you don’t want the handling of the request to go through handle_errors, then yes.