简体   繁体   English

libxml2错误处理

[英]libxml2 error handling

I'm writing a small wrapper around libxml2 in C++, and I'm trying to work out how to handle errors. 我正在用C ++在libxml2周围编写一个小型包装程序,并且正在尝试找出如何处理错误。 For now, let's say I just want to print them out. 现在,假设我只想打印出来。 Here's what I've got at present: 这是我目前所拥有的:

My error handling function: 我的错误处理功能:

void foo(void *ctx, const char *msg, ...) {
  cout << msg << endl;
  return;
}

Initialised like this: 像这样初始化:

xmlGenericErrorFunc handler = (xmlGenericErrorFunc)foo;
initGenericErrorDefaultFunc(&handler);

However, if I parse a bad XPath, I get this output: 但是,如果我解析了一个错误的XPath,则会得到以下输出:

%s

Without the error handling code, I get this: 没有错误处理代码,我得到以下信息:

XPath error : Invalid expression
//.@foobar
    ^

Obviously eventually my error handling will do more than just print out the error message (it'll log it to a database or something), but for now - how can I get that error string? 显然,最终我的错误处理将不仅仅是打印错误消息(它将记录到数据库或其他内容),还可以做更多的事情,但是现在,我如何获得该错误字符串?

The three dots at the end of the argument list for you function foo() means it takes a variable amount of arguments. 函数foo()的参数列表末尾的三个点表示需要可变数量的参数。 To be able to print those you could do something like this (not tested): 为了能够打印这些,您可以执行以下操作(未测试):

#include <stdarg.h>

#define TMP_BUF_SIZE 256
void foo(void *ctx, const char *msg, ...) {
   char string[TMP_BUF_SIZE];
   va_list arg_ptr;

   va_start(arg_ptr, msg);
   vsnprintf(string, TMP_BUF_SIZE, msg, arg_ptr);
   va_end(arg_ptr);
   cout << string << endl;
   return;
}

As already pointed out if this is your handling function: 如前所述,这是否是您的处理函数:

#define TMP_BUF_SIZE 256
void err(void *ctx, const char *msg, ...) {
   char string[TMP_BUF_SIZE];
   va_list arg_ptr;
   va_start(arg_ptr, msg);
   vsnprintf(string, TMP_BUF_SIZE, msg, arg_ptr);
   va_end(arg_ptr);
   cout << string << endl;
   return;
}

you can set it with this libxml2 function 您可以使用此libxml2函数进行设置

xmlSetGenericErrorFunc(NULL,gemXmlGenericErrorFunc);

if you have a context to pass, ie some struct,data,class whatever pointer casted to void*, you can put it as first argument. 如果您有要传递的上下文,即某些struct,data,class转换为void *的任何指针,则可以将其作为第一个参数。

Note that foo will be called a lot, for instance if you have a parse error each time libxml adds a line to the error message. 请注意,foo将被大量调用,例如,如果每次libxml在错误消息中添加一行,则您都会遇到解析错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM