Skip to content

Commit

Permalink
NOISSUE - New error type for HTTP Proxy server to return Handlers err…
Browse files Browse the repository at this point in the history
…or (#50)

* add http error type

Signed-off-by: Arvindh <[email protected]>

* refactor(errors.go): reorder code into new file

Signed-off-by: Felix Gateru <[email protected]>

* remove MG errors

Signed-off-by: Arvindh <[email protected]>

* remove MG errors

Signed-off-by: Arvindh <[email protected]>

---------

Signed-off-by: Arvindh <[email protected]>
Signed-off-by: Felix Gateru <[email protected]>
Co-authored-by: Felix Gateru <[email protected]>
  • Loading branch information
arvindh123 and felixgateru authored Oct 17, 2024
1 parent 6bc4b2b commit e53a940
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
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

0 comments on commit e53a940

Please sign in to comment.