#include "api/ApiErrorDecoder.hpp"
#include <vector>
#include "core/JsonDecode.hpp"
#include "spec/ApiPaths.hpp"
#include "spec/UiMessages.hpp"
namespace dp {
namespace {
std::vector<std::string> stringArray(const Json& array, const char* key) {
return JsonDecode::list<std::string>(array, key, [key](const Json& v) { return JsonDecode::convert<std::string>(v, key); });
}
} // namespace
std::optional<ApiErrorDecoder::Decoded> 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<std::string> messages;
if (auto it = j.find("messages"); it != j.end() && !it->is_null()) messages = stringArray(*it, "messages");
std::optional<std::string> specific;
if (error.is_string()) {
specific = messages.empty() ? error.get<std::string>() : messages.front();
} else if (error.is_object()) {
(void)D::opt<std::int64_t>(error, "status"); // parsed, never used (type checked like Swift)
auto message = D::opt<std::string>(error, "message");
std::vector<std::string> 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