我是protobuf(C ++)的新手,我的代码在解析消息期间失败。如何获得有关发生的错误的更多详细信息?
例子
以下代码段说明了该问题:
const bool ok=my_message.ParseFromCodedStream(&stream);
if(ok){
std::cout<< "message parsed. evidence:\n"<< my_message.DebugString();
}
else{
std::cerr<< "error parsing protobuf\n";
//HOW CAN I GET A REASON FOR THE FAILURE HERE?
}
如果您查看protobuf代码,就会发现它使用的是自己的基于宏的日志记录系统。默认情况下,所有这些消息都发送到stderr
,但是您可以使用SetLogHandler()
以下命令在程序中捕获它们:
typedef void LogHandler(LogLevel level, const char* filename, int line,
const std::string& message);
可能的解决方案是建立自己的类似errno
机制(对C ++ 11-ishness感到抱歉):
typedef LogMessage std::tuple<LogLevel, std::string, int, std::string>; // C++11
typedef LogStack std::list<LogMessage>;
namespace {
LogStack stack;
bool my_errno;
} // namespace
void MyLogHandler(LogLevel level, const char* filename, int line,
const std::string& message) {
stack.push_back({level, filename, line, message}); // C++11.
my_errno = true;
}
protobuf::SetLogHandler(MyLogHandler);
bool GetError(LogStack* my_stack) {
if (my_errno && my_stack) {
// Dump collected logs.
my_stack->assign(stack.begin(), stack.end());
}
stack.clear();
bool old_errno = my_errno;
my_errno = false;
return old_errno;
}
并在您的代码中使用它:
...
else {
std::cerr<< "error parsing protobuf" << std::endl;
LogStack my_stack;
if (GetError(&my_stack) {
// Handle your errors here.
}
}
我的示例代码的主要缺点-不适用于多个线程。但这可以自己解决。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句