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