Skip to content

Instantly share code, notes, and snippets.

@groob

groob/err.go Secret

Created October 28, 2016 23:19
Show Gist options
  • Save groob/ff49f470eeb389c7aa237e667beab326 to your computer and use it in GitHub Desktop.
Save groob/ff49f470eeb389c7aa237e667beab326 to your computer and use it in GitHub Desktop.
func encodeError(ctx context.Context, err error, w http.ResponseWriter) {
// Unwrap Go-Kit Error
domain := "service"
if e, ok := err.(kithttp.Error); ok {
err = e.Err
domain = e.Domain
}
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
type validationError interface {
Invalid() []map[string]string
}
if e, ok := err.(validationError); ok {
ve := jsonError{
Message: "Validation Failed",
Errors: e.Invalid(),
}
w.WriteHeader(http.StatusUnprocessableEntity)
enc.Encode(ve)
return
}
type authenticationError interface {
AuthError() string
}
if e, ok := err.(authenticationError); ok {
ae := jsonError{
Message: "Authentication Failed",
Error: e.AuthError(),
}
w.WriteHeader(http.StatusUnauthorized)
enc.Encode(ae)
return
}
type permissionError interface {
PermissionError() []map[string]string
}
if e, ok := err.(permissionError); ok {
pe := jsonError{
Message: "Permission Denied",
Errors: e.PermissionError(),
}
w.WriteHeader(http.StatusForbidden)
enc.Encode(pe)
return
}
// Other errors
switch domain {
case "service":
w.WriteHeader(codeFromErr(err))
case kithttp.DomainDecode:
w.WriteHeader(http.StatusBadRequest)
case kithttp.DomainDo:
w.WriteHeader(http.StatusServiceUnavailable)
default:
w.WriteHeader(http.StatusInternalServerError)
}
enc.Encode(map[string]interface{}{
"error": err.Error(),
})
}
func codeFromErr(err error) int {
switch err {
case datastore.ErrNotFound:
return http.StatusNotFound
case datastore.ErrExists:
return http.StatusConflict
default:
return http.StatusInternalServerError
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment