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