Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NOISSUE - New error type for HTTP Proxy server to return Handlers error #50

Merged
merged 4 commits into from
Oct 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions pkg/http/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Copyright (c) Abstract Machines
// SPDX-License-Identifier: Apache-2.0

package http

import "encoding/json"

type httpProxyError struct {
statusCode int
err error
}

type HTTPProxyError interface {
error
MarshalJSON() ([]byte, error)
StatusCode() int
}

var _ HTTPProxyError = (*httpProxyError)(nil)

func (hpe *httpProxyError) Error() string {
return hpe.err.Error()
}

func (hpe *httpProxyError) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Error string `json:"error"`
}{
Error: hpe.err.Error(),
})
}

func (hpe *httpProxyError) StatusCode() int {
return hpe.statusCode
}

func NewHTTPProxyError(statusCode int, err error) HTTPProxyError {
return &httpProxyError{statusCode: statusCode, err: err}
}
8 changes: 6 additions & 2 deletions pkg/http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,12 @@ func (p Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
p.target.ServeHTTP(w, r)
}

func encodeError(w http.ResponseWriter, statusCode int, err error) {
w.WriteHeader(statusCode)
func encodeError(w http.ResponseWriter, defStatusCode int, err error) {
hpe, ok := err.(HTTPProxyError)
if !ok {
hpe = NewHTTPProxyError(defStatusCode, err)
}
w.WriteHeader(hpe.StatusCode())
w.Header().Set("Content-Type", contentType)
if err := json.NewEncoder(w).Encode(err); err != nil {
w.WriteHeader(http.StatusInternalServerError)
Expand Down
Loading