errors.cpp 2.4 KB

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