github.com/volatiletech/authboss@v2.4.1+incompatible/defaults/error_handler.go (about)

     1  package defaults
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  
     7  	"github.com/volatiletech/authboss"
     8  )
     9  
    10  // ErrorHandler wraps http handlers with errors with itself
    11  // to provide error handling.
    12  //
    13  // The pieces provided to this struct must be thread-safe
    14  // since they will be handed to many pointers to themselves.
    15  type ErrorHandler struct {
    16  	LogWriter authboss.Logger
    17  }
    18  
    19  // NewErrorHandler constructor
    20  func NewErrorHandler(logger authboss.Logger) ErrorHandler {
    21  	return ErrorHandler{LogWriter: logger}
    22  }
    23  
    24  // Wrap an http handler with an error
    25  func (e ErrorHandler) Wrap(handler func(w http.ResponseWriter, r *http.Request) error) http.Handler {
    26  	return errorHandler{
    27  		Handler:   handler,
    28  		LogWriter: e.LogWriter,
    29  	}
    30  }
    31  
    32  type errorHandler struct {
    33  	Handler   func(w http.ResponseWriter, r *http.Request) error
    34  	LogWriter authboss.Logger
    35  }
    36  
    37  // ServeHTTP handles errors
    38  func (e errorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    39  	err := e.Handler(w, r)
    40  	if err == nil {
    41  		return
    42  	}
    43  
    44  	e.LogWriter.Error(fmt.Sprintf("request error from (%s) %s: %+v", r.RemoteAddr, r.URL.String(), err))
    45  }