Skip to content

Custom error handler for httputil.ReverseProxy #14329

Closed
@sosedoff

Description

@sosedoff

Current implementation of httputil.ReverseProxy is pretty handy and useful,
however there's one small issue with error handling: there's no easy way to
override or customize error response.

Here's the current error handling code:

res, err := transport.RoundTrip(outreq)
if err != nil {
  p.logf("http: proxy error: %v", err)
  rw.WriteHeader(http.StatusInternalServerError)
  return
}

Perhaps having a error handler func on ReverseProxy struct might be a good idea:

type ReverseProxy struct {
  // ... existing code ...

  // Handler function that will be invoked when proxy request fails due to 
  // various reasons (timeout, connection refused, etc)
  ErrorHandler func(error, http.ResponseWriter,*http.Request)
}

If ErrorHandler is not provided proxy will keep the existing behavior, otherwise
it'll pass error handling to our custom function.

Example:

proxy := httputil.NewSingleHostReverseProxy(target)
proxy.ErrorHandler = func(err error, w http.ResponseWriter, r *http.Request) {
  // check error type and do something
  // ....
  // respond with some other status code
  w.WriteHeader(http.StatusServiceUnavailable)
}

Any thoughts?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions