errors.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #include "errors.hpp"
  2. namespace svapi {
  3. int httpStatus(ErrCode code) {
  4. switch (code) {
  5. case ErrCode::BadRequest: return 400;
  6. case ErrCode::Unauthorized: return 401;
  7. case ErrCode::Forbidden: return 403;
  8. case ErrCode::NotFound: return 404;
  9. case ErrCode::Conflict: return 409;
  10. case ErrCode::Unprocessable: return 422;
  11. case ErrCode::TooManyRequests: return 429;
  12. case ErrCode::Unavailable: return 503;
  13. // A function that ran past its wall-time budget. 504 rather than 408:
  14. // nothing was slow about the client, the upstream we were waiting on
  15. // did not answer. Nothing but function dispatch produces this.
  16. case ErrCode::GatewayTimeout: return 504;
  17. // The DATABASE is too old to perform what was asked - not a fault of
  18. // ours and not a fault of the caller's. 501 rather than 503, because
  19. // 503 means "retry as-is" and no amount of retrying upgrades a
  20. // database; rather than 422, because the request is perfectly valid
  21. // and there is nothing in the body to correct. The remedy is an
  22. // operator action, so the status has to say "this server cannot do
  23. // this" instead of blaming either side.
  24. case ErrCode::NotImplemented: return 501;
  25. case ErrCode::Internal: return 500;
  26. }
  27. return 500;
  28. }
  29. int retryAfterSeconds(const ApiError& e) {
  30. // The raise site's own hint first: it knew the cause.
  31. if (e.retryAfterSec > 0) return e.retryAfterSec;
  32. // Then the one status whose duration is a property of the status itself.
  33. if (e.code == ErrCode::TooManyRequests) return kRetryAfterRateLimitedSec;
  34. // And otherwise nothing. See the note on ApiError::retryAfterSec: silence
  35. // is the honest answer for a failure whose remedy has no duration.
  36. return 0;
  37. }
  38. nlohmann::json errorBody(const std::string& code, const std::string& message,
  39. const nlohmann::json& details) {
  40. nlohmann::json err{{"code", code}, {"message", message}};
  41. if (!details.is_null() && !details.empty()) err["details"] = details;
  42. return nlohmann::json{{"error", err}};
  43. }
  44. } // namespace svapi