qapi: add QAPI dealloc visitor
[qemu/mdroth.git] / error.c
blob74d7398b586e688a96c8bdd2fda0d27248867df7
1 /*
2 * QEMU Error Objects
4 * Copyright IBM, Corp. 2011
6 * Authors:
7 * Anthony Liguori <aliguori@us.ibm.com>
9 * This work is licensed under the terms of the GNU LGPL, version 2. See
10 * the COPYING.LIB file in the top-level directory.
13 #include "qemu-common.h"
14 #include "error.h"
15 #include "error_int.h"
16 #include "qemu-objects.h"
17 #include "qerror.h"
19 struct Error
21 QDict *obj;
22 const char *fmt;
23 char *msg;
26 void error_set(Error **errp, const char *fmt, ...)
28 Error *err;
29 va_list ap;
31 if (errp == NULL) {
32 return;
35 err = qemu_mallocz(sizeof(*err));
37 va_start(ap, fmt);
38 err->obj = qobject_to_qdict(qobject_from_jsonv(fmt, &ap));
39 va_end(ap);
40 err->fmt = fmt;
42 *errp = err;
45 bool error_is_set(Error **errp)
47 return (errp && *errp);
50 const char *error_get_pretty(Error *err)
52 if (err->msg == NULL) {
53 QString *str;
54 str = qerror_format(err->fmt, err->obj);
55 err->msg = qemu_strdup(qstring_get_str(str));
56 QDECREF(str);
59 return err->msg;
62 const char *error_get_field(Error *err, const char *field)
64 if (strcmp(field, "class") == 0) {
65 return qdict_get_str(err->obj, field);
66 } else {
67 QDict *dict = qdict_get_qdict(err->obj, "data");
68 return qdict_get_str(dict, field);
72 QDict *error_get_data(Error *err)
74 QDict *data = qdict_get_qdict(err->obj, "data");
75 QINCREF(data);
76 return data;
79 void error_set_field(Error *err, const char *field, const char *value)
81 QDict *dict = qdict_get_qdict(err->obj, "data");
82 return qdict_put(dict, field, qstring_from_str(value));
85 void error_free(Error *err)
87 if (err) {
88 QDECREF(err->obj);
89 qemu_free(err->msg);
90 qemu_free(err);
94 bool error_is_type(Error *err, const char *fmt)
96 const char *error_class;
97 char *ptr;
98 char *end;
100 ptr = strstr(fmt, "'class': '");
101 assert(ptr != NULL);
102 ptr += strlen("'class': '");
104 end = strchr(ptr, '\'');
105 assert(end != NULL);
107 error_class = error_get_field(err, "class");
108 if (strlen(error_class) != end - ptr) {
109 return false;
112 return strncmp(ptr, error_class, end - ptr) == 0;
115 void error_propagate(Error **dst_err, Error *local_err)
117 if (dst_err) {
118 *dst_err = local_err;
119 } else if (local_err) {
120 error_free(local_err);
124 QObject *error_get_qobject(Error *err)
126 QINCREF(err->obj);
127 return QOBJECT(err->obj);
130 void error_set_qobject(Error **errp, QObject *obj)
132 Error *err;
133 if (errp == NULL) {
134 return;
136 err = qemu_mallocz(sizeof(*err));
137 err->obj = qobject_to_qdict(obj);
138 qobject_incref(obj);
140 *errp = err;