91ee45edff2ae19d1c263f2754afe61854a673ed
[libjh.git] / error.c
1 // Copyright (2013) Jann Horn <jann@thejh.net>
2
3 // This file contains stuff for making error-handling easier.
4
5 #include <stdlib.h>
6
7 #define GENERIC_ERROR \
8   "unexpected generic failure of some kind"
9
10 PUBLIC_FN void xperror(const char *s, int show_errno) {
11   if (!s) s=GENERIC_ERROR;
12   if (show_errno) {
13     perror(s);
14   } else {
15     fprintf(stderr, "%s\n", s);
16   }
17   exit(1);
18 }
19
20 PUBLIC_FN void *fail_on_npointer(void *p, char *msg, int show_errno) {
21   if (!p) xperror(msg, show_errno);
22   return p;
23 }
24
25 HEADER #define CHK_PTR(p, msg, show_errno) (        \
26 HEADER   (typeof (p))                               \
27 HEADER   fail_on_npointer((p), (msg), (show_errno)) \
28 HEADER )
29
30 PUBLIC_FN int fail_on_neg(int n, char *msg, int show_errno) {
31   if ((n)<0) xperror(msg, show_errno);
32   return n;
33 }