1
0
mirror of https://github.com/rancher/norman.git synced 2025-09-16 07:09:44 +00:00

API error improvements

Log underlying causes of APIErrors (if it is available).
Also, some general cleanup.
This commit is contained in:
Craig Jellick
2018-02-15 16:55:23 -07:00
parent 6753a90143
commit daaccc2c2c
2 changed files with 19 additions and 4 deletions

View File

@@ -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}
@@ -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 {
@@ -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,
@@ -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,
@@ -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
}

View File

@@ -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)