error, qerror: add ErrorClass argument to error functions
[qemu.git] / error.c
blob648706aa678a025cf0052964c15943b9506003e6
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 "qjson.h"
16 #include "qdict.h"
17 #include "qapi-types.h"
18 #include "error_int.h"
19 #include "qerror.h"
21 struct Error
23 QDict *obj;
24 char *msg;
25 ErrorClass err_class;
28 void error_set(Error **errp, ErrorClass err_class, const char *fmt, ...)
30 Error *err;
31 va_list ap;
33 if (errp == NULL) {
34 return;
36 assert(*errp == NULL);
38 err = g_malloc0(sizeof(*err));
40 va_start(ap, fmt);
41 err->obj = qobject_to_qdict(qobject_from_jsonv(fmt, &ap));
42 va_end(ap);
43 err->msg = qerror_format(fmt, err->obj);
44 err->err_class = err_class;
46 *errp = err;
49 Error *error_copy(const Error *err)
51 Error *err_new;
53 err_new = g_malloc0(sizeof(*err));
54 err_new->msg = g_strdup(err->msg);
55 err_new->err_class = err->err_class;
56 err_new->obj = err->obj;
57 QINCREF(err_new->obj);
59 return err_new;
62 bool error_is_set(Error **errp)
64 return (errp && *errp);
67 const char *error_get_pretty(Error *err)
69 return err->msg;
72 const char *error_get_field(Error *err, const char *field)
74 if (strcmp(field, "class") == 0) {
75 return qdict_get_str(err->obj, field);
76 } else {
77 QDict *dict = qdict_get_qdict(err->obj, "data");
78 return qdict_get_str(dict, field);
82 QDict *error_get_data(Error *err)
84 QDict *data = qdict_get_qdict(err->obj, "data");
85 QINCREF(data);
86 return data;
89 void error_set_field(Error *err, const char *field, const char *value)
91 QDict *dict = qdict_get_qdict(err->obj, "data");
92 qdict_put(dict, field, qstring_from_str(value));
95 void error_free(Error *err)
97 if (err) {
98 QDECREF(err->obj);
99 g_free(err->msg);
100 g_free(err);
104 bool error_is_type(Error *err, ErrorClass err_class, const char *fmt)
106 const char *error_class;
107 char *ptr;
108 char *end;
110 if (!err) {
111 return false;
114 ptr = strstr(fmt, "'class': '");
115 assert(ptr != NULL);
116 ptr += strlen("'class': '");
118 end = strchr(ptr, '\'');
119 assert(end != NULL);
121 error_class = error_get_field(err, "class");
122 if (strlen(error_class) != end - ptr) {
123 return false;
126 return strncmp(ptr, error_class, end - ptr) == 0;
129 void error_propagate(Error **dst_err, Error *local_err)
131 if (dst_err && !*dst_err) {
132 *dst_err = local_err;
133 } else if (local_err) {
134 error_free(local_err);
138 QObject *error_get_qobject(Error *err)
140 QINCREF(err->obj);
141 return QOBJECT(err->obj);
144 void error_set_qobject(Error **errp, QObject *obj)
146 Error *err;
147 if (errp == NULL) {
148 return;
150 err = g_malloc0(sizeof(*err));
151 err->obj = qobject_to_qdict(obj);
152 qobject_incref(obj);
154 *errp = err;