errors.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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/admin"
  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 *admin.Error:
  21. admin.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 if e, ok := cause.(errs.StackTracer); ok {
  49. rl.WithFields(map[string]interface{}{
  50. "stack-trace": fmt.Sprintf("%+v", e),
  51. })
  52. }
  53. }
  54. }
  55. if err := json.NewEncoder(w).Encode(err); err != nil {
  56. LogError(w, err)
  57. }
  58. }