protobuf中的错误处理

Error handling in protobuf

本文关键字:处理 错误 protobuf      更新时间:2023-10-16

我是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;
    }

当程序运行时,它只显示错误消息,但不显示任何原因。我如何才能得到错误的原因?

Protobuf解析失败的原因有两个:
  • 输入数据缺少必填字段。在这种情况下,Protobuf库会编写一条描述问题的日志消息,然后返回false。在这种情况下,日志处理程序将收到错误消息。

  • 输入数据不是有效的Protobuf(它已损坏,或者从一开始就不是Protobuf)。在这种情况下,Protobuf库只是返回false,没有任何错误消息。图书馆在这里真的没有什么有用的信息可以提供。如果发生这种情况,最好的调试方法是在序列化消息之后和解析消息之前转储确切的字节,然后查找差异。