errors.hpp 1.1 KB

1234567891011121314151617181920212223242526272829
  1. #pragma once
  2. #include <stdexcept>
  3. #include <string>
  4. #include <nlohmann/json.hpp>
  5. namespace svapi {
  6. enum class ErrCode { BadRequest, Unauthorized, Forbidden, NotFound, Conflict,
  7. Unprocessable, TooManyRequests, Unavailable, GatewayTimeout,
  8. Internal };
  9. int httpStatus(ErrCode code);
  10. /// `details` is merged into the error object as `error.details` when non-empty.
  11. /// Used for machine-readable payloads (colliding ids, relation impacts) that
  12. /// would otherwise be flattened into the message string.
  13. nlohmann::json errorBody(const std::string& code, const std::string& message,
  14. const nlohmann::json& details = nlohmann::json::object());
  15. struct ApiError : std::runtime_error {
  16. ErrCode code;
  17. std::string slug;
  18. nlohmann::json details; // optional structured payload; empty object = omitted
  19. ApiError(ErrCode c, std::string slug_, const std::string& msg,
  20. nlohmann::json det = nlohmann::json::object())
  21. : std::runtime_error(msg), code(c), slug(std::move(slug_)), details(std::move(det)) {}
  22. };
  23. } // namespace svapi