protobuf中的错误处理

时间:2015-02-13 11:11:41

标签: c++ protocol-buffers

我是protobuf(C ++)的新手,并尝试使用protobuf编写第一个测试程序。 代码是

#include <cstdlib>
#include <iostream>
#include "proto/req.pb.h"

using namespace std;
using namespace google::protobuf;

int main(int argc, char** argv) {
      std::string s = "asdfasdf";

        auto MyLogHandler = [] (google::protobuf::LogLevel level, const char* filename, int line, const std::string& message)
        {
            std::cout << "message " << message << std::endl;
        };
        google::protobuf::SetLogHandler(MyLogHandler);

        Request req;
        if ( req.ParseFromString(s)){
            cout << "Parse - OK" << endl;
        }else{
               cout << "Parse - ERROR" << endl;
        }
        return 0;
    }

程序运行时 - 它只显示错误信息,但没有任何理由。我怎样才能得出错误的原因?

1 个答案:

答案 0 :(得分:3)

Protobuf解析有两个原因可能会失败:

  • 输入数据缺少必填字段。在这种情况下,Protobuf库会写入描述问题的日志消息,然后返回false。在这种情况下,您的日志处理程序将收到错误消息。

  • 输入数据不是有效的Protobuf(它是腐败的,或者从来就不是protobuf)。在这种情况下,Protobuf库只返回false而没有任何错误消息。图书馆在这里没有提供有用的信息。如果您遇到这种情况,最好的调试方法是在序列化消息之后立即转储确切的字节,然后再解析它,然后查找差异。