如何为多个C库创建常见的错误处理机制?
我的库(liba)的每个源文件都包括一个in_err.h文件。
该文件为每个可能的错误定义了枚举,以及描述相应错误的字符串数组。
有一个函数get_err_mess(),该函数返回与错误枚举相对应的错误消息。
in_err.h
typedef enum {
E_ERR_NOERROR = OK, //OK=0
E_ERR_1 = E_ERR_BADPARAM,
...
E_ERR_MAX
} ERROR;
const char *error_description[] = {
"No error.",
"Bad parameter.",
...
"Max error enum reached.",
};
const char * get_err_mess(ERROR err){
...
return err_mess;
}
我库(liba)的每个功能都返回错误类型。
liba.a
#include "in_err.h"
ERROR func1()
{
ERROR err = OK;
...
return err
}
主程序调用liba的函数,并显示错误消息(如果有)。
main.c
#include "in_err.h"
#include "headerfromlibA.h"
int main()
{
ERROR err = OK;
err = func1()
if (!err){
err = func2()
}
if(err){
printf("Error: %s\n", get_err_mess(err));
}
return err;
}
现在我想用相同的错误管理制作另一个库(libb),但具有自己的错误类型。
我的问题是我将有两个get_err_mess()功能具有相同的错误ID。
我想拥有一个get_err_mess()来管理liba和libb的错误。
您会推荐什么?
我看到的唯一解决方案是为每个库设置一系列错误...但是我不喜欢
Each source file of my library (libA) includes an in_err.h file.
This file defines an enum for every possible error, and an array of string describing the corresponding error.
There is a function get_err_mess() which returns the error message corresponding to the error enum.
in_err.h
typedef enum {
E_ERR_NOERROR = OK, //OK=0
E_ERR_1 = E_ERR_BADPARAM,
...
E_ERR_MAX
} ERROR;
const char *error_description[] = {
"No error.",
"Bad parameter.",
...
"Max error enum reached.",
};
const char * get_err_mess(ERROR err){
...
return err_mess;
}
Every functions of my library (libA) returns an ERROR type.
libA.a
#include "in_err.h"
ERROR func1()
{
ERROR err = OK;
...
return err
}
The main program calls functions from libA and displays error message if any.
main.c
#include "in_err.h"
#include "headerfromlibA.h"
int main()
{
ERROR err = OK;
err = func1()
if (!err){
err = func2()
}
if(err){
printf("Error: %s\n", get_err_mess(err));
}
return err;
}
Now I want to make another library (libB) with the same kind of error management but with its own types of errors.
My problem is that I would have two get_err_mess() functions with potentially the same error id.
I'd like to have a single get_err_mess() to manage errors from libA and libB.
What would you recommend ?
The only solution I see is to set a range of error for each library... but I don't like it
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
基本思想:返回堆栈上的16字节结构(
uniform_error
)。err.h
:liba.h
:liba.c
:libb.h
:libb.c.c
:main.c
:输出:
Basic idea: return a 16-byte struct (
UNIFORM_ERROR
below) on the stack.err.h
:liba.h
:liba.c
:libb.h
:libb.c
:main.c
:output: