errors.go 1.5 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. w.Header().Set("Content-Type", "application/problem+json")
  18. err = k.ToACME()
  19. case *scep.Error:
  20. // TODO: check if this is correct; and should we do some more processing?
  21. w.Header().Set("Content-Type", "text/plain")
  22. default:
  23. w.Header().Set("Content-Type", "application/json")
  24. }
  25. cause := errors.Cause(err)
  26. if sc, ok := err.(errs.StatusCoder); ok {
  27. w.WriteHeader(sc.StatusCode())
  28. } else {
  29. if sc, ok := cause.(errs.StatusCoder); ok {
  30. w.WriteHeader(sc.StatusCode())
  31. } else {
  32. w.WriteHeader(http.StatusInternalServerError)
  33. }
  34. }
  35. // Write errors in the response writer
  36. if rl, ok := w.(logging.ResponseLogger); ok {
  37. rl.WithFields(map[string]interface{}{
  38. "error": err,
  39. })
  40. if os.Getenv("STEPDEBUG") == "1" {
  41. if e, ok := err.(errs.StackTracer); ok {
  42. rl.WithFields(map[string]interface{}{
  43. "stack-trace": fmt.Sprintf("%+v", e),
  44. })
  45. } else {
  46. if e, ok := cause.(errs.StackTracer); ok {
  47. rl.WithFields(map[string]interface{}{
  48. "stack-trace": fmt.Sprintf("%+v", e),
  49. })
  50. }
  51. }
  52. }
  53. }
  54. if err := json.NewEncoder(w).Encode(err); err != nil {
  55. LogError(w, err)
  56. }
  57. }