errors.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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/authority/mgmt"
  10. "github.com/smallstep/certificates/errs"
  11. "github.com/smallstep/certificates/logging"
  12. "github.com/smallstep/certificates/scep"
  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 *mgmt.Error:
  21. mgmt.WriteError(w, k)
  22. return
  23. case *scep.Error:
  24. w.Header().Set("Content-Type", "text/plain")
  25. default:
  26. w.Header().Set("Content-Type", "application/json")
  27. }
  28. cause := errors.Cause(err)
  29. if sc, ok := err.(errs.StatusCoder); ok {
  30. w.WriteHeader(sc.StatusCode())
  31. } else {
  32. if sc, ok := cause.(errs.StatusCoder); ok {
  33. w.WriteHeader(sc.StatusCode())
  34. } else {
  35. w.WriteHeader(http.StatusInternalServerError)
  36. }
  37. }
  38. // Write errors in the response writer
  39. if rl, ok := w.(logging.ResponseLogger); ok {
  40. rl.WithFields(map[string]interface{}{
  41. "error": err,
  42. })
  43. if os.Getenv("STEPDEBUG") == "1" {
  44. if e, ok := err.(errs.StackTracer); ok {
  45. rl.WithFields(map[string]interface{}{
  46. "stack-trace": fmt.Sprintf("%+v", e),
  47. })
  48. } else {
  49. if e, ok := cause.(errs.StackTracer); ok {
  50. rl.WithFields(map[string]interface{}{
  51. "stack-trace": fmt.Sprintf("%+v", e),
  52. })
  53. }
  54. }
  55. }
  56. }
  57. if err := json.NewEncoder(w).Encode(err); err != nil {
  58. LogError(w, err)
  59. }
  60. }