errors.go 1.3 KB

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