| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- #include "errors.hpp"
- #include "request_trace.hpp"
- namespace svapi {
- int httpStatus(ErrCode code) {
- switch (code) {
- case ErrCode::BadRequest: return 400;
- case ErrCode::Unauthorized: return 401;
- case ErrCode::Forbidden: return 403;
- case ErrCode::NotFound: return 404;
- case ErrCode::Conflict: return 409;
- case ErrCode::Unprocessable: return 422;
- case ErrCode::TooManyRequests: return 429;
- case ErrCode::Unavailable: return 503;
- // A function that ran past its wall-time budget. 504 rather than 408:
- // nothing was slow about the client, the upstream we were waiting on
- // did not answer. Nothing but function dispatch produces this.
- case ErrCode::GatewayTimeout: return 504;
- // The DATABASE is too old to perform what was asked - not a fault of
- // ours and not a fault of the caller's. 501 rather than 503, because
- // 503 means "retry as-is" and no amount of retrying upgrades a
- // database; rather than 422, because the request is perfectly valid
- // and there is nothing in the body to correct. The remedy is an
- // operator action, so the status has to say "this server cannot do
- // this" instead of blaming either side.
- case ErrCode::NotImplemented: return 501;
- case ErrCode::Internal: return 500;
- }
- return 500;
- }
- int retryAfterSeconds(const ApiError& e) {
- // The raise site's own hint first: it knew the cause.
- if (e.retryAfterSec > 0) return e.retryAfterSec;
- // Then the one status whose duration is a property of the status itself.
- if (e.code == ErrCode::TooManyRequests) return kRetryAfterRateLimitedSec;
- // And otherwise nothing. See the note on ApiError::retryAfterSec: silence
- // is the honest answer for a failure whose remedy has no duration.
- return 0;
- }
- nlohmann::json errorBody(const std::string& code, const std::string& message,
- const nlohmann::json& details) {
- // EVERY refusal passes through here, which is why the access log's slug is
- // recorded at this one point rather than at the exception handler alone.
- // See access_log.hpp for what that fixed.
- noteRequestErrorCode(code);
- nlohmann::json err{{"code", code}, {"message", message}};
- if (!details.is_null() && !details.empty()) err["details"] = details;
- return nlohmann::json{{"error", err}};
- }
- } // namespace svapi
|