<commit_before>package respond

import (
	"fmt"
	"net/http"
	"respond/middleware"
)

type ServerErrorEndpointFunc func(http.ResponseWriter, *http.Request, error) error

type ErrorHandlerMiddleware struct {
	ServerErrorEndpoint ServerErrorEndpointFunc
}

func NewErrorHandlerMiddleware(errorPageEndpoint ServerErrorEndpointFunc) *ErrorHandlerMiddleware {
	return &ErrorHandlerMiddleware{
		ServerErrorEndpoint: errorPageEndpoint,
	}
}

func (errorHandler *ErrorHandlerMiddleware) Process (response http.ResponseWriter, request *http.Request,
	next middleware.NextFunc) (returnError error) {

	defer func() {

		if recovered := recover(); recovered != nil {

			response.WriteHeader(500)

			var err error
			
			if e, ok := recovered.(error); ok {
				err = e
			} else {
				err = fmt.Errorf("%+v", e)
			}			

			err = errorHandler.ServerErrorEndpoint(response, request, err)

			if err != nil {
				returnError = fmt.Errorf("%s", err)
			}
		}
	}()

	if err := next(response); err != nil {
		panic(err)
	}<commit_msg>error handler middleware respect status codes of errors return from upstream middlewares<commit_after>package respond

import (
	"fmt"
	"net/http"
	"respond/middleware"
)

type ServerErrorEndpointFunc func(http.ResponseWriter, *http.Request, error) error

type StatusCodedError interface {
	HTTPStatusCode() int
}

type ErrorHandlerMiddleware struct {
	ServerErrorEndpoint ServerErrorEndpointFunc
}

func NewErrorHandlerMiddleware(errorPageEndpoint ServerErrorEndpointFunc) *ErrorHandlerMiddleware {
	return &ErrorHandlerMiddleware{
		ServerErrorEndpoint: errorPageEndpoint,
	}
}

func (errorHandler *ErrorHandlerMiddleware) Process (response http.ResponseWriter, request *http.Request,
	next middleware.NextFunc) (returnError error) {

	defer func() {

		if recovered := recover(); recovered != nil {

			var err error
			
			if e, ok := recovered.(error); ok {
				err = e
			} else {
				err = fmt.Errorf("%+v", e)
			}

			if statusCodedError, ok := err.(StatusCodedError); ok {
				response.WriteHeader(statusCodedError.HTTPStatusCode())
			} else {
				response.WriteHeader(500)
			}

			err = errorHandler.ServerErrorEndpoint(response, request, err)

			if err != nil {
				returnError = fmt.Errorf("%s", err)
			}
		}
	}()

	if err := next(response); err != nil {
		panic(err)
	}
{'fraction_non_alphanumeric': 0.10797918473547267, 'fraction_numerical': 0.0026019080659150044, 'mean_word_length': 4.402810304449648, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1750337', 'n_tokens_mistral': 772, 'n_tokens_neox': 687, 'n_words': 173}