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