errors.hpp 1.1 KB

12345678910111213141516171819202122232425262728
  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, Internal };
  8. int httpStatus(ErrCode code);
  9. /// `details` is merged into the error object as `error.details` when non-empty.
  10. /// Used for machine-readable payloads (colliding ids, relation impacts) that
  11. /// would otherwise be flattened into the message string.
  12. nlohmann::json errorBody(const std::string& code, const std::string& message,
  13. const nlohmann::json& details = nlohmann::json::object());
  14. struct ApiError : std::runtime_error {
  15. ErrCode code;
  16. std::string slug;
  17. nlohmann::json details; // optional structured payload; empty object = omitted
  18. ApiError(ErrCode c, std::string slug_, const std::string& msg,
  19. nlohmann::json det = nlohmann::json::object())
  20. : std::runtime_error(msg), code(c), slug(std::move(slug_)), details(std::move(det)) {}
  21. };
  22. } // namespace svapi