打印错误信息 [英] Printing error messages

查看:114
本文介绍了打印错误信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道什么是使自定义打印误差函数的最佳方式。

I am just wondering what is the best way to make custom print error functions.

例如我在头文件中的#define一些这样的:

For example I have some #defines like this in header file:

#define SOCKET_ERR 0
#define BIND_ERR   1
#define LISTEN_ERR 2 
etc

那么也许使用这个是这样的:

Then maybe using this like this:

if(/*something has gone wrong with socket*/)
{
   print_error(SOCKET_ERR);
}

print_error(int error)
{
   if(error == 0)
   {
       printf("Socket failure\n");
   }
}

不过,我不认为这完美的,想要做的事要好得多。或许真的有点更专业,也许更多的可伸缩性。

However, I don't think this perfect and want to do something much better. Maybe something a little bit more professional and maybe more scalable.

非常感谢任何建议,

推荐答案

您可能会考虑使用参数可变型函数错误报告,他们变得​​更加灵活。

You might consider using variadic functions for error reporting, they become so much more versatile.

例如

#include <stdarg.h>
void my_error(FILE *out, const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    vfprintf(out, fmt, ap);
    va_end(ap);
}

这可能是调用像这样(注意,我假设一个C99编译):

Which could be invoked like this (note, I'm assuming a c99 compiler):

my_error(stderr,
    "%s: Invalid range of %ld near line %d", __func__, range, __LINE__);

这可以很容易地与其他答案提示错误codeS可在枚举列表中定义,以字符串常量数组把它们翻译配合。我会离开,作为一个练习留给读者。它很容易使上面的例子中接受更多的参数。

This could easily tie in with other answers suggesting that error codes could be defined in enumerated lists, with a constant array of strings to translate them. I'll leave that as an exercise for the reader. Its very easy to make the example above accept more arguments.

注意:如果你使用类似字符缓冲区[LEN]将自定义格式打印字符串,它从虚空到unsigned int类型的变化,有它返回vsnprintf(字节数)无法打印,这可能是有用的呼叫者。上面的例子是安全的,其中你不必担心在使用未定义长度的格式错误信息流动的一些堆栈分配的缓冲区。或者,把它作为无效,并把它打印什么可以(但同时指出它无法打印的所有内容),给你。平局回到这个方法不是很了解的可变参数的长度一度扩大。毕竟,你要回报意想不到的结果:)

NB: If you use something like char buffer[LEN] to custom format the printed string, change it from void to unsigned int, have it return the number of bytes that vsnprintf() could not print, that might be useful to the caller. The above example is 'safe', wherein you don't have to worry about over flowing some stack allocated buffer with a formatted error message of undefined length. Or, leave it as void and have it print what it can (while noting it could not print everything), up to you. The draw back to this approach is not quite knowing the length of the variadic arguments once expanded. After all, you're reporting unexpected results :)

此方法,您可以帮助自己更转达有意义的信息的错误信息,以及简单地将它们记录到任何打开的文件。

This approach lets you help yourself more by conveying meaningful and informative error messages, as well as simply logging them to any open file.

我知道,这个例子描述了基本的printf()本身。我张贴这表明它是多么容易调整和扩展。

I know that this example basically describes printf() itself. I'm posting it to show how easy it is to adapt and expand.

这篇关于打印错误信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆