PdsError PdsClientImpl::buildError()

in sdk/src/PdsClientImpl.cc [219:289]


PdsError PdsClientImpl::buildError(const Error &error) const
{
    PdsError err;
    if (((error.Status() == 203) || (error.Status() > 299 && error.Status() < 600)) &&
        !error.Message().empty()) {
        std::string contentType;
        auto it = error.Headers().find("Content-Type");
        if (it != error.Headers().end()) {
            contentType = it->second;
        }
        if (contentType.find("application/json") != contentType.npos) {
            Json::Value root;
            Json::CharReaderBuilder rbuilder;
            std::string errMsg;
            std::stringstream msg;
            msg << error.Message();
            if (Json::parseFromStream(rbuilder, msg, &root, &errMsg))
            {
                err.setCode(root["code"].asString());
                err.setMessage(root["message"].asString());
            } else {
                std::stringstream ss;
                ss << "ParseJSONError:" << errMsg;
                err.setCode("ParseJSONError");
                err.setMessage(ss.str());
            }
        } else if (contentType.find("application/xml") != contentType.npos) {
            XMLDocument doc;
            XMLError xml_err;
            if ((xml_err = doc.Parse(error.Message().c_str(), error.Message().size())) == XML_SUCCESS) {
                XMLElement* root =doc.RootElement();
                if (root && !std::strncmp("Error", root->Name(), 5)) {
                    XMLElement *node;
                    node = root->FirstChildElement("Code");
                    err.setCode(node ? node->GetText(): "");
                    node = root->FirstChildElement("Message");
                    err.setMessage(node ? node->GetText(): "");
                    node = root->FirstChildElement("RequestId");
                    err.setRequestId(node ? node->GetText(): "");
                    node = root->FirstChildElement("HostId");
                    err.setHost(node ? node->GetText(): "");
                } else {
                    err.setCode("ParseXMLError");
                    err.setMessage("Xml format invalid, root node name is not Error. the content is:\n" + error.Message());
                }
            } else {
                std::stringstream ss;
                ss << "ParseXMLError:" << xml_err;
                err.setCode(ss.str());
                err.setMessage(XMLDocument::ErrorIDToName(xml_err));
            }
        } else {
            err.setCode(error.Code());
            err.setMessage(error.Message());
        }
    }
    else {
        err.setCode(error.Code());
        err.setMessage(error.Message());
    }

    //get from header if body has nothing
    if (err.RequestId().empty()) {
        auto it = error.Headers().find("x-ca-request-id");
        if (it != error.Headers().end()) {
            err.setRequestId(it->second);
        }
    }

    return err;
}