c - 确定错误的原始原因

标签 c error-handling

在 C 中是否有一些众所周知的嵌套错误处理模式/实践,例如 Java 中的嵌套异常?

通常的“只返回错误代码/成功”错误细节可能会在程序确定它应该记录/报告错误之前丢失。

想象一个类似这样的代码:

err B()
{
  if (read(a/b/c/U.user) != OK) {
    return read_error; //which would be eaccess or we could return even e_cannot_read_user
  }

  if (is_empty(read_user.name)) {
    // we could tell exactly what is missing here
    return einval;
  }
  ...
}

err A()
{
  if (B() != OK) {
    if (cannot_handle_B_failing()) {
      return e_could_not_do_b;
    }
  }
  ...
}

main()
{
  ...
  if (A() != OK) && (no_alternative_solution()) {
    report error_returned_by_A;
    wait_for_more_user_input();
  }
}

有没有人在这种情况下成功地尝试过在 C 中使用某种嵌套的错误代码/消息?可以报​​告(主要)用户名丢失或由于权限无效而无法读取文件 F 的事实。

有库支持这样的东西吗?

最佳答案

我建议你看看Apple's error handling guideline .它是为 Objective-C 设计的,主要类是 NSError。他们使用 userInfo 字典(映射)来保存有关错误的详细信息,并且他们预定义了 NSUnderlyingErrorKey 常量来保存底层 NSError 对象如果需要的话,那本字典。

因此您可以为您的代码声明您自己的错误struct 并实现类似的解决方案。

例如

typedef struct {
  int code;
  struct Error *underlyingError;
  char domain[0];
} Error;

然后您可以使用 domain 字段对错误进行分类(根据需要按库、文件或函数); code 字段用于确定错误本身,可选的 underlyingError 字段用于找出导致您收到错误的潜在错误。

关于c - 确定错误的原始原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46529124/

相关文章:

c - 尝试使用 fgets 读取两行。为什么它只读第一行?

wordpress - 未定义索引: alqnas in public_html/wp-cron.php on line 3

php - php mysql如何解决此错误:Undefined variable :id in C:\

Python Moviepy 模块 : output video?

powershell - PowerShell和进程退出代码

c - inputSex() 和 inputAge() 的返回值没有返回任何内容?

c - gcc 原子内置函数

c - Makefile:为什么带有 % 的 makefile 不起作用?

从 char 函数中删除 printf 后的 C : Program prints weird stuff in output,

php - php restore_error_handler无法正常工作