add stuff for error-handling
authorJann Horn <jann@thejh.net>
Tue, 20 Aug 2013 16:18:20 +0000 (18:18 +0200)
committerJann Horn <jann@thejh.net>
Tue, 20 Aug 2013 16:18:20 +0000 (18:18 +0200)
error.c [new file with mode: 0644]

diff --git a/error.c b/error.c
new file mode 100644 (file)
index 0000000..9727253
--- /dev/null
+++ b/error.c
@@ -0,0 +1,34 @@
+// Copyright (2013) Jann Horn <jann@thejh.net>
+// This code is licensed under the AGPLv3.
+
+// This file contains stuff for making error-handling easier.
+
+#include <stdlib.h>
+
+#define GENERIC_ERROR \
+  "unexpected generic failure of some kind"
+
+PUBLIC_FN void xperror(const char *s, int show_errno) {
+  if (!s) s=GENERIC_ERROR;
+  if (show_errno) {
+    perror(s);
+  } else {
+    fprintf(stderr, "%s\n", s);
+  }
+  exit(1);
+}
+
+PUBLIC_FN void *fail_on_npointer(void *p, char *msg, int show_errno) {
+  if (!p) xperror(msg, show_errno);
+  return p;
+}
+
+HEADER #define CHK_PTR(p, msg, show_errno) (        \
+HEADER   (typeof (p))                               \
+HEADER   fail_on_npointer((p), (msg), (show_errno)) \
+HEADER )
+
+PUBLIC_FN int fail_on_neg(int n, char *msg, int show_errno) {
+  if ((n)<0) xperror(msg, show_errno);
+  return n;
+}