internal: move HTTPError to common file

This is used by both clients and servers now.
This commit is contained in:
Simon Ser 2020-05-13 18:24:29 +02:00
parent a4e0e81003
commit 25df841e2b
No known key found for this signature in database
GPG Key ID: 0FDE7BE0E88F5E48
2 changed files with 34 additions and 33 deletions

View File

@ -3,6 +3,7 @@ package internal
import (
"fmt"
"net/http"
)
// Depth indicates whether a request applies to the resource's members. It's
@ -65,3 +66,36 @@ func FormatOverwrite(overwrite bool) string {
return "F"
}
}
type HTTPError struct {
Code int
Err error
}
func HTTPErrorFromError(err error) *HTTPError {
if err == nil {
return nil
}
if httpErr, ok := err.(*HTTPError); ok {
return httpErr
} else {
return &HTTPError{http.StatusInternalServerError, err}
}
}
func IsNotFound(err error) bool {
return HTTPErrorFromError(err).Code == http.StatusNotFound
}
func HTTPErrorf(code int, format string, a ...interface{}) *HTTPError {
return &HTTPError{code, fmt.Errorf(format, a...)}
}
func (err *HTTPError) Error() string {
s := fmt.Sprintf("%v %v", err.Code, http.StatusText(err.Code))
if err.Err != nil {
return fmt.Sprintf("%v: %v", s, err.Err)
} else {
return s
}
}

View File

@ -9,39 +9,6 @@ import (
"strings"
)
type HTTPError struct {
Code int
Err error
}
func HTTPErrorFromError(err error) *HTTPError {
if err == nil {
return nil
}
if httpErr, ok := err.(*HTTPError); ok {
return httpErr
} else {
return &HTTPError{http.StatusInternalServerError, err}
}
}
func IsNotFound(err error) bool {
return HTTPErrorFromError(err).Code == http.StatusNotFound
}
func HTTPErrorf(code int, format string, a ...interface{}) *HTTPError {
return &HTTPError{code, fmt.Errorf(format, a...)}
}
func (err *HTTPError) Error() string {
s := fmt.Sprintf("%v %v", err.Code, http.StatusText(err.Code))
if err.Err != nil {
return fmt.Sprintf("%v: %v", s, err.Err)
} else {
return s
}
}
func ServeError(w http.ResponseWriter, err error) {
code := http.StatusInternalServerError
if httpErr, ok := err.(*HTTPError); ok {