4
0

errors.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. "github.com/pkg/errors"
  8. "github.com/smallstep/certificates/acme"
  9. "github.com/smallstep/certificates/api/log"
  10. "github.com/smallstep/certificates/authority/admin"
  11. "github.com/smallstep/certificates/errs"
  12. "github.com/smallstep/certificates/logging"
  13. )
  14. // WriteError writes to w a JSON representation of the given error.
  15. func WriteError(w http.ResponseWriter, err error) {
  16. switch k := err.(type) {
  17. case *acme.Error:
  18. acme.WriteError(w, k)
  19. return
  20. case *admin.Error:
  21. admin.WriteError(w, k)
  22. return
  23. }
  24. cause := errors.Cause(err)
  25. // Write errors in the response writer
  26. if rl, ok := w.(logging.ResponseLogger); ok {
  27. rl.WithFields(map[string]interface{}{
  28. "error": err,
  29. })
  30. if os.Getenv("STEPDEBUG") == "1" {
  31. if e, ok := err.(errs.StackTracer); ok {
  32. rl.WithFields(map[string]interface{}{
  33. "stack-trace": fmt.Sprintf("%+v", e),
  34. })
  35. } else if e, ok := cause.(errs.StackTracer); ok {
  36. rl.WithFields(map[string]interface{}{
  37. "stack-trace": fmt.Sprintf("%+v", e),
  38. })
  39. }
  40. }
  41. }
  42. code := http.StatusInternalServerError
  43. if sc, ok := err.(errs.StatusCoder); ok {
  44. code = sc.StatusCode()
  45. } else if sc, ok := cause.(errs.StatusCoder); ok {
  46. code = sc.StatusCode()
  47. }
  48. w.Header().Set("Content-Type", "application/json")
  49. w.WriteHeader(code)
  50. if err := json.NewEncoder(w).Encode(err); err != nil {
  51. log.Error(w, err)
  52. }
  53. }