错误处理

Proj维护内部错误状态,该状态是 PJ_CONTEXT 线程上下文。

看见 快速启动 有关如何创建和使用线程上下文对象的详细信息。

如果从项目API函数收到异常返回(例如空指针),您可能希望发现有关该错误的更多信息。

在这种情况下,您可以调用 proj_context_errno() ,传入您的线程上下文。这将返回一个整型错误代码。

如果错误代码为零,则认为上次项目操作成功,未检测到任何错误。

如果错误代码非零,则表示检测到错误。您可以将线程上下文与此错误代码一起传递给 proj_context_errno_string() 检索描述错误条件的字符串。

下面是一个显示C程序如何捕获和报告错误的基本示例:

errorhandling.c
 1  #include <stdio.h>
 2  #include <proj.h>
 3
 4  int main (void) {
 5      PJ_CONTEXT *c;
 6      PJ *p;
 7      int errno;
 8      const char *errstr;
 9
10      c = proj_context_create();
11      p = proj_create_crs_to_crs(c, "EPSG:4326", "EPSG:3857", NULL);
12
13      if (p == 0) {
14          /* Something is wrong, let's try to get details ... */
15          errno = proj_context_errno(c);
16          if (errno == 0) {
17              /* This should be impossible. */
18              fprintf(stderr, "Failed to create transformation, reason unknown.\n");
19          } else {
20              errstr = proj_context_errno_string(c, errno);
21              fprintf(stderr, "Failed to create transformation: %s.\n", errstr);
22          }
23          proj_context_destroy(c);
24          return 1;
25      }
26
27      /* transformation object is valid, do work ... */
28
29      proj_destroy(p);
30      proj_context_destroy(c);
31
32      return 0;
33  }