Files
zeekay 241625e7d9 rename: ziti → zt across all paths
- Repo names: ziti-* → zt-*
- Go modules: github.com/hanzozt/ziti → github.com/hanzozt/zt
- Docker images: hanzozt/ziti-* → hanzozt/zt-*
- C/Java/JS symbols: ziti_* → zt_*
- File and directory names updated
2026-02-18 18:34:19 -08:00

71 lines
2.5 KiB
Go

package env
import (
"net/http"
openApiErrors "github.com/go-openapi/errors"
"github.com/michaelquigley/pfxlog"
"github.com/hanzozt/foundation/v2/errorz"
"github.com/hanzozt/zt/v2/controller/apierror"
)
// ServeError is a wrapper for the OpenAPI REST server to allow the Edge API Error message responses to be used
// when errors are raised from the OpenAPI internal runtimes. This includes input validation methods,
// unsupported media types, etc.
func ServeError(rw http.ResponseWriter, r *http.Request, inErr error) {
if openApiError, ok := inErr.(openApiErrors.Error); ok {
//openApiErrors from the Open API framework mean that we never hit any of the Edge logic and thus
//do not have any context established (i.e. no request id)
var apiError *errorz.ApiError
if openApiError.Code() == http.StatusUnprocessableEntity {
// triggered by validation failures and consumer errors
var newApiError *errorz.ApiError
if compositeError, ok := openApiError.(*openApiErrors.CompositeError); ok {
if len(compositeError.Errors) > 0 {
//validation errors
if validationError, ok := compositeError.Errors[0].(*openApiErrors.Validation); ok {
newApiError = errorz.NewCouldNotValidate(validationError)
newApiError.Status = int(validationError.Code())
}
}
}
// only other option is could not parse
if newApiError == nil {
newApiError = apierror.NewCouldNotParseBody(openApiError)
}
apiError = newApiError
} else if openApiError.Code() == http.StatusNotFound {
// handle open API openApiErrors we have existing ApiErrors for
apiError = errorz.NewNotFound()
} else if openApiError.Code() == http.StatusMethodNotAllowed {
apiError = apierror.NewMethodNotAllowed()
} else if openApiError.Code() == http.StatusUnauthorized {
apiError = errorz.NewUnauthorized()
} else if openApiError.Code() == http.StatusForbidden {
apiError = errorz.NewUnauthorized()
} else if openApiError.Code() >= 600 && openApiError.Code() < 700 {
//openapi defines error codes 601+ for validation errors
apiError = errorz.NewCouldNotValidate(inErr)
} else {
apiError = errorz.NewUnhandled(openApiError)
}
apiError.Cause = openApiError
NewRequestContext(rw, r).RespondWithApiError(apiError)
return
}
requestContext, err := GetRequestContextFromHttpContext(r)
if requestContext == nil || err != nil {
pfxlog.Logger().WithError(err).Error("failed to retrieve request context")
requestContext = NewRequestContext(rw, r)
}
requestContext.RespondWithError(inErr)
}