#include "api/ApiErrorDecoder.hpp" #include #include "core/JsonDecode.hpp" #include "spec/ApiPaths.hpp" #include "spec/UiMessages.hpp" namespace dp { namespace { std::vector stringArray(const Json& array, const char* key) { return JsonDecode::list(array, key, [key](const Json& v) { return JsonDecode::convert(v, key); }); } } // namespace std::optional ApiErrorDecoder::decodeBody(const std::string& body) { using D = JsonDecode; try { const Json j = Json::parse(body); const Json& error = D::child(j, "error"); std::vector messages; if (auto it = j.find("messages"); it != j.end() && !it->is_null()) messages = stringArray(*it, "messages"); std::optional specific; if (error.is_string()) { specific = messages.empty() ? error.get() : messages.front(); } else if (error.is_object()) { (void)D::opt(error, "status"); // parsed, never used (type checked like Swift) auto message = D::opt(error, "message"); std::vector errors; if (auto it = error.find("errors"); it != error.end() && !it->is_null()) errors = stringArray(*it, "errors"); if (message) specific = message; else if (!errors.empty()) specific = errors.front(); else if (!messages.empty()) specific = messages.front(); } else { return std::nullopt; } if (specific) return Decoded{*specific, true}; return Decoded{spec::UiMessages::kSomethingWentWrong, false}; } catch (const std::exception&) { return std::nullopt; } } Error ApiErrorDecoder::fromResponse(int status, const std::string& body) { const bool unauthorized = status == spec::HttpSpec::kUnauthorizedStatus; if (auto decoded = decodeBody(body)) { return Error{unauthorized ? Error::Kind::Unauthorized : Error::Kind::Api, status, decoded->message, decoded->isSpecific}; } return Error{unauthorized ? Error::Kind::Unauthorized : Error::Kind::Http, status, spec::UiMessages::kSomethingWentWrong, false}; } } // namespace dp