gpt4 book ai didi

c - 在 C 中处理来自多个库的错误代码

转载 作者:太空狗 更新时间:2023-10-29 17:25:38 25 4
gpt4 key购买 nike

很多时候,我必须使用多个以不同方式处理错误或为错误定义自己的枚举的库。这使得编写可能必须处理来自不同来源的错误然后返回其自己的错误代码的函数变得困难。例如:

int do_foo_and_bar()
{
int err;
if ((err = libfoo_do_something()) < 0) {
// return err and indication that it was caused by foo
}
if ((err = libbar_do_something()) < 0) {
// return err and indication that it was caused by bar
}
// ...
return 0;
}

我想到了两种可能的解决方案:

  • 使用 int translate_foo_error(int err) 等函数创建我自己的错误代码列表并将这些错误代码转换为新的错误代码,并且我会为每个错误编写我自己的字符串表示。<
  • 创建一个struct my_error,其中包含标识库的枚举和错误代码。字符串的翻译将委托(delegate)给每个库的适当函数。

这似乎是一个经常出现的问题,所以我很好奇,通常如何处理?似乎前者是大多数图书馆所做的,但后者工作较少,并且使用已经提供的工具。大多数教程只是向 stderr 打印一条消息并在出现任何错误时退出,这无济于事。我宁愿让每个函数都指出出了什么问题,调用者可以据此决定如何处理它。

最佳答案

答案是,这取决于您的代码的约束。

collectd打印到标准错误,然后在遇到 fatal error 时退出。

OpenGL 将设置一些您可以查询的共享状态。忽略此错误通常会导致未定义的行为。

Collectd 有很多线程问题,大多数错误无法由程序修复或恢复。例如,如果一个插件依赖于某个库,而对该库的调用失败,则该插件最了解如何从该错误中恢复。冒泡这个错误是没有帮助的,因为 collectd 核心永远不会知道插件 N+1

另一方面,OpenGL 应用程序通常对遇到的任何错误负责,并且可以尝试更正错误。例如,如果他们正在尝试编译着色器,但可能有针对特定供应商或平台的特殊着色器。

根据您的程序设计,考虑以下因素:

  1. 冒出错误会让你做出更好的决定吗?
    • 来电者是否知道您的实现?他们应该吗?
  2. 您的应用程序是否可以纠正可能出现的错误?
    • 例如如果您无法打开套接字或文件,您可以重试或失败,仅此而已。
  3. 如果您创建一个 GetLastError() 函数,是否对全局状态有限制?

更新:

使用全局状态选项你可能会有这样的东西:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>

char* last_err = NULL;

void set_err(char* error_message) {
if(last_err)
free(last_err);
/* Make a deep copy to be safe.
* The error string might be dynamically allocated by an external library.
* We can't know for sure where it came from.
*/
last_err = strdup(error_message);
}

int can_sqrt(int a) {
if(a < 0) {
set_err("We can't take the square root of a negative number");
return 0;
}
return 1;
}

int main(int argc, char* argv[]) {
int i = 1;
for(i = 1; i < argc; i++) {
int square = atoi(argv[i]);
if(can_sqrt(square)) {
fprintf(stdout, "the square root of %d is: %.0f\n", square, sqrt(square));
} else {
fprintf(stderr, "%s\n", last_err);
}
}
return 0;
}

运行上面的程序

$ ./a.out -1 2 -4 0 -6 4
We can't take the square root of a negative number
the square root of 2 is: 1
We can't take the square root of a negative number
the square root of 0 is: 0
We can't take the square root of a negative number
the square root of 4 is: 2

关于c - 在 C 中处理来自多个库的错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24624543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com