Skip to content

Commit

Permalink
Merge pull request #97 from cjellick/api-errors
Browse files Browse the repository at this point in the history
API error improvements
  • Loading branch information
Craig Jellick authored Feb 16, 2018
2 parents 6753a90 + daaccc2 commit 193c79e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
19 changes: 15 additions & 4 deletions httperror/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ import (
)

var (
Unauthorized = ErrorCode{"Unauthorized", 401}
PermissionDenied = ErrorCode{"PermissionDenied", 403}
NotFound = ErrorCode{"NotFound", 404}
MethodNotAllowed = ErrorCode{"MethodNotAllow", 405}

InvalidDateFormat = ErrorCode{"InvalidDateFormat", 422}
InvalidFormat = ErrorCode{"InvalidFormat", 422}
InvalidReference = ErrorCode{"InvalidReference", 422}
Expand All @@ -23,12 +28,9 @@ var (
InvalidType = ErrorCode{"InvalidType", 422}
ActionNotAvailable = ErrorCode{"ActionNotAvailable", 404}
InvalidState = ErrorCode{"InvalidState", 422}

ServerError = ErrorCode{"ServerError", 500}
ClusterUnavailable = ErrorCode{"ClusterUnavailable", 503}
PermissionDenied = ErrorCode{"PermissionDenied", 403}

MethodNotAllowed = ErrorCode{"MethodNotAllow", 405}
NotFound = ErrorCode{"NotFound", 404}
)

type ErrorCode struct {
Expand Down Expand Up @@ -69,6 +71,8 @@ func NewFieldAPIError(code ErrorCode, fieldName, message string) error {
}
}

// WrapFieldAPIError will cause the API framework to log the underlying err before returning the APIError as a response.
// err WILL NOT be in the API response
func WrapFieldAPIError(err error, code ErrorCode, fieldName, message string) error {
return &APIError{
Cause: err,
Expand All @@ -78,6 +82,8 @@ func WrapFieldAPIError(err error, code ErrorCode, fieldName, message string) err
}
}

// WrapAPIError will cause the API framework to log the underlying err before returning the APIError as a response.
// err WILL NOT be in the API response
func WrapAPIError(err error, code ErrorCode, message string) error {
return &APIError{
code: code,
Expand All @@ -92,3 +98,8 @@ func (a *APIError) Error() string {
}
return fmt.Sprintf("%s: %s", a.code, a.message)
}

func IsAPIError(err error) bool {
_, ok := err.(*APIError)
return ok
}
4 changes: 4 additions & 0 deletions httperror/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ import (
func ErrorHandler(request *types.APIContext, err error) {
var error *APIError
if apiError, ok := err.(*APIError); ok {
if apiError.Cause != nil {
logrus.Errorf("API error response %v for %v %v. Cause: %v", apiError.code.Status, request.Request.Method,
request.Request.RequestURI, apiError.Cause)
}
error = apiError
} else {
logrus.Errorf("Unknown error: %v", err)
Expand Down

0 comments on commit 193c79e

Please sign in to comment.