util: add ErrInternal

ErrInternal is an internal error that should be provided to the user (http api
will return a 500 with the error message)

It'll be used for any kind of error that are not auth or bad requests (like
errors to communicate to another service)
This commit is contained in:
Simone Gotti 2019-06-11 10:59:21 +02:00
parent 580746d7f1
commit 6e8d467c80
4 changed files with 39 additions and 0 deletions

View File

@ -49,6 +49,10 @@ func ErrorResponseFromError(err error) *ErrorResponse {
var cerr *util.ErrUnauthorized
errors.As(err, &cerr)
aerr = cerr
case errors.Is(err, &util.ErrInternal{}):
var cerr *util.ErrInternal
errors.As(err, &cerr)
aerr = cerr
}
if aerr != nil {
@ -83,6 +87,9 @@ func httpError(w http.ResponseWriter, err error) bool {
case errors.Is(err, &util.ErrUnauthorized{}):
w.WriteHeader(http.StatusUnauthorized)
w.Write(resj)
case errors.Is(err, &util.ErrInternal{}):
w.WriteHeader(http.StatusInternalServerError)
w.Write(resj)
default:
w.WriteHeader(http.StatusInternalServerError)
w.Write(resj)

View File

@ -50,6 +50,10 @@ func ErrorResponseFromError(err error) *ErrorResponse {
var cerr *util.ErrUnauthorized
errors.As(err, &cerr)
aerr = cerr
case errors.Is(err, &util.ErrInternal{}):
var cerr *util.ErrInternal
errors.As(err, &cerr)
aerr = cerr
}
if aerr != nil {
@ -84,6 +88,9 @@ func httpError(w http.ResponseWriter, err error) bool {
case errors.Is(err, &util.ErrUnauthorized{}):
w.WriteHeader(http.StatusUnauthorized)
w.Write(resj)
case errors.Is(err, &util.ErrInternal{}):
w.WriteHeader(http.StatusInternalServerError)
w.Write(resj)
default:
w.WriteHeader(http.StatusInternalServerError)
w.Write(resj)

View File

@ -66,6 +66,10 @@ func ErrorResponseFromError(err error) *ErrorResponse {
var cerr *util.ErrUnauthorized
errors.As(err, &cerr)
aerr = cerr
case errors.Is(err, &util.ErrInternal{}):
var cerr *util.ErrInternal
errors.As(err, &cerr)
aerr = cerr
}
if aerr != nil {
@ -100,6 +104,9 @@ func httpError(w http.ResponseWriter, err error) bool {
case errors.Is(err, &util.ErrUnauthorized{}):
w.WriteHeader(http.StatusUnauthorized)
w.Write(resj)
case errors.Is(err, &util.ErrInternal{}):
w.WriteHeader(http.StatusInternalServerError)
w.Write(resj)
default:
w.WriteHeader(http.StatusInternalServerError)
w.Write(resj)

View File

@ -131,3 +131,21 @@ func (*ErrUnauthorized) Is(err error) bool {
_, ok := err.(*ErrUnauthorized)
return ok
}
type ErrInternal struct {
Err error
}
// ErrInternal represent an internal error that should be returned to the user
func (e *ErrInternal) Error() string {
return e.Err.Error()
}
func NewErrInternal(err error) *ErrInternal {
return &ErrInternal{Err: err}
}
func (*ErrInternal) Is(err error) bool {
_, ok := err.(*ErrInternal)
return ok
}