handler.go 996 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package errcode
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. )
  6. // ServeJSON attempts to serve the errcode in a JSON envelope. It marshals err
  7. // and sets the content-type header to 'application/json'. It will handle
  8. // ErrorCoder and Errors, and if necessary will create an envelope.
  9. func ServeJSON(w http.ResponseWriter, err error) error {
  10. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  11. var sc int
  12. switch errs := err.(type) {
  13. case Errors:
  14. if len(errs) < 1 {
  15. break
  16. }
  17. if err, ok := errs[0].(ErrorCoder); ok {
  18. sc = err.ErrorCode().Descriptor().HTTPStatusCode
  19. }
  20. case ErrorCoder:
  21. sc = errs.ErrorCode().Descriptor().HTTPStatusCode
  22. err = Errors{err} // create an envelope.
  23. default:
  24. // We just have an unhandled error type, so just place in an envelope
  25. // and move along.
  26. err = Errors{err}
  27. }
  28. if sc == 0 {
  29. sc = http.StatusInternalServerError
  30. }
  31. w.WriteHeader(sc)
  32. if err := json.NewEncoder(w).Encode(err); err != nil {
  33. return err
  34. }
  35. return nil
  36. }