1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * SPDX-License-Identifier: LGPL-2.1-or-later
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
21 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
22 * file for a list of people on the GLib Team. See the ChangeLog
23 * files for a list of changes. These files are distributed with
24 * GLib at ftp://ftp.gtk.org/pub/gtk/.
28 * SECTION:error_reporting
29 * @Title: Error Reporting
30 * @Short_description: a system for reporting errors
32 * GLib provides a standard method of reporting errors from a called
33 * function to the calling code. (This is the same problem solved by
34 * exceptions in other languages.) It's important to understand that
35 * this method is both a data type (the #GError struct) and a [set of
36 * rules][gerror-rules]. If you use #GError incorrectly, then your code will not
37 * properly interoperate with other code that uses #GError, and users
38 * of your API will probably get confused. In most cases, [using #GError is
39 * preferred over numeric error codes][gerror-comparison], but there are
40 * situations where numeric error codes are useful for performance.
42 * First and foremost: #GError should only be used to report recoverable
43 * runtime errors, never to report programming errors. If the programmer
44 * has screwed up, then you should use g_warning(), g_return_if_fail(),
45 * g_assert(), g_error(), or some similar facility. (Incidentally,
46 * remember that the g_error() function should only be used for
47 * programming errors, it should not be used to print any error
48 * reportable via #GError.)
50 * Examples of recoverable runtime errors are "file not found" or
51 * "failed to parse input." Examples of programming errors are "NULL
52 * passed to strcmp()" or "attempted to free the same pointer twice."
53 * These two kinds of errors are fundamentally different: runtime errors
54 * should be handled or reported to the user, programming errors should
55 * be eliminated by fixing the bug in the program. This is why most
56 * functions in GLib and GTK do not use the #GError facility.
58 * Functions that can fail take a return location for a #GError as their
59 * last argument. On error, a new #GError instance will be allocated and
60 * returned to the caller via this argument. For example:
61 * |[<!-- language="C" -->
62 * gboolean g_file_get_contents (const gchar *filename,
67 * If you pass a non-%NULL value for the `error` argument, it should
68 * point to a location where an error can be placed. For example:
69 * |[<!-- language="C" -->
73 * g_file_get_contents ("foo.txt", &contents, NULL, &err);
74 * g_assert ((contents == NULL && err != NULL) || (contents != NULL && err == NULL));
77 * // Report error to user, and free error
78 * g_assert (contents == NULL);
79 * fprintf (stderr, "Unable to read file: %s\n", err->message);
84 * // Use file contents
85 * g_assert (contents != NULL);
88 * Note that `err != NULL` in this example is a reliable indicator
89 * of whether g_file_get_contents() failed. Additionally,
90 * g_file_get_contents() returns a boolean which
91 * indicates whether it was successful.
93 * Because g_file_get_contents() returns %FALSE on failure, if you
94 * are only interested in whether it failed and don't need to display
95 * an error message, you can pass %NULL for the @error argument:
96 * |[<!-- language="C" -->
97 * if (g_file_get_contents ("foo.txt", &contents, NULL, NULL)) // ignore errors
98 * // no error occurred
105 * The #GError object contains three fields: @domain indicates the module
106 * the error-reporting function is located in, @code indicates the specific
107 * error that occurred, and @message is a user-readable error message with
108 * as many details as possible. Several functions are provided to deal
109 * with an error received from a called function: g_error_matches()
110 * returns %TRUE if the error matches a given domain and code,
111 * g_propagate_error() copies an error into an error location (so the
112 * calling function will receive it), and g_clear_error() clears an
113 * error location by freeing the error and resetting the location to
114 * %NULL. To display an error to the user, simply display the @message,
115 * perhaps along with additional context known only to the calling
116 * function (the file being opened, or whatever - though in the
117 * g_file_get_contents() case, the @message already contains a filename).
119 * Since error messages may be displayed to the user, they need to be valid
120 * UTF-8 (all GTK widgets expect text to be UTF-8). Keep this in mind in
121 * particular when formatting error messages with filenames, which are in
122 * the 'filename encoding', and need to be turned into UTF-8 using
123 * g_filename_to_utf8(), g_filename_display_name() or g_utf8_make_valid().
125 * Note, however, that many error messages are too technical to display to the
126 * user in an application, so prefer to use g_error_matches() to categorize errors
127 * from called functions, and build an appropriate error message for the context
128 * within your application. Error messages from a #GError are more appropriate
129 * to be printed in system logs or on the command line. They are typically
132 * When implementing a function that can report errors, the basic
133 * tool is g_set_error(). Typically, if a fatal error occurs you
134 * want to g_set_error(), then return immediately. g_set_error()
135 * does nothing if the error location passed to it is %NULL.
137 * |[<!-- language="C" -->
139 * foo_open_file (GError **error)
144 * g_return_val_if_fail (error == NULL || *error == NULL, -1);
146 * fd = open ("file.txt", O_RDONLY);
147 * saved_errno = errno;
151 * g_set_error (error,
152 * FOO_ERROR, // error domain
153 * FOO_ERROR_BLAH, // error code
154 * "Failed to open file: %s", // error message format string
155 * g_strerror (saved_errno));
163 * Things are somewhat more complicated if you yourself call another
164 * function that can report a #GError. If the sub-function indicates
165 * fatal errors in some way other than reporting a #GError, such as
166 * by returning %TRUE on success, you can simply do the following:
167 * |[<!-- language="C" -->
169 * my_function_that_can_fail (GError **err)
171 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
173 * if (!sub_function_that_can_fail (err))
175 * // assert that error was set by the sub-function
176 * g_assert (err == NULL || *err != NULL);
180 * // otherwise continue, no error occurred
181 * g_assert (err == NULL || *err == NULL);
185 * If the sub-function does not indicate errors other than by
186 * reporting a #GError (or if its return value does not reliably indicate
187 * errors) you need to create a temporary #GError
188 * since the passed-in one may be %NULL. g_propagate_error() is
189 * intended for use in this case.
190 * |[<!-- language="C" -->
192 * my_function_that_can_fail (GError **err)
196 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
199 * sub_function_that_can_fail (&tmp_error);
201 * if (tmp_error != NULL)
203 * // store tmp_error in err, if err != NULL,
204 * // otherwise call g_error_free() on tmp_error
205 * g_propagate_error (err, tmp_error);
209 * // otherwise continue, no error occurred
213 * Error pileups are always a bug. For example, this code is incorrect:
214 * |[<!-- language="C" -->
216 * my_function_that_can_fail (GError **err)
220 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
223 * sub_function_that_can_fail (&tmp_error);
224 * other_function_that_can_fail (&tmp_error);
226 * if (tmp_error != NULL)
228 * g_propagate_error (err, tmp_error);
233 * @tmp_error should be checked immediately after sub_function_that_can_fail(),
234 * and either cleared or propagated upward. The rule is: after each error,
235 * you must either handle the error, or return it to the calling function.
237 * Note that passing %NULL for the error location is the equivalent
238 * of handling an error by always doing nothing about it. So the
239 * following code is fine, assuming errors in sub_function_that_can_fail()
240 * are not fatal to my_function_that_can_fail():
241 * |[<!-- language="C" -->
243 * my_function_that_can_fail (GError **err)
247 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
249 * sub_function_that_can_fail (NULL); // ignore errors
252 * other_function_that_can_fail (&tmp_error);
254 * if (tmp_error != NULL)
256 * g_propagate_error (err, tmp_error);
262 * Note that passing %NULL for the error location ignores errors;
264 * `try { sub_function_that_can_fail (); } catch (...) {}`
265 * in C++. It does not mean to leave errors unhandled; it means
266 * to handle them by doing nothing.
268 * Error domains and codes are conventionally named as follows:
270 * - The error domain is called <NAMESPACE>_<MODULE>_ERROR,
271 * for example %G_SPAWN_ERROR or %G_THREAD_ERROR:
272 * |[<!-- language="C" -->
273 * #define G_SPAWN_ERROR g_spawn_error_quark ()
275 * G_DEFINE_QUARK (g-spawn-error-quark, g_spawn_error)
278 * - The quark function for the error domain is called
279 * <namespace>_<module>_error_quark,
280 * for example g_spawn_error_quark() or g_thread_error_quark().
282 * - The error codes are in an enumeration called
283 * <Namespace><Module>Error;
284 * for example, #GThreadError or #GSpawnError.
286 * - Members of the error code enumeration are called
287 * <NAMESPACE>_<MODULE>_ERROR_<CODE>,
288 * for example %G_SPAWN_ERROR_FORK or %G_THREAD_ERROR_AGAIN.
290 * - If there's a "generic" or "unknown" error code for unrecoverable
291 * errors it doesn't make sense to distinguish with specific codes,
292 * it should be called <NAMESPACE>_<MODULE>_ERROR_FAILED,
293 * for example %G_SPAWN_ERROR_FAILED. In the case of error code
294 * enumerations that may be extended in future releases, you should
295 * generally not handle this error code explicitly, but should
296 * instead treat any unrecognized error code as equivalent to
299 * ## Comparison of #GError and traditional error handling # {#gerror-comparison}
301 * #GError has several advantages over traditional numeric error codes:
302 * importantly, tools like
303 * [gobject-introspection](https://developer.gnome.org/gi/stable/) understand
304 * #GErrors and convert them to exceptions in bindings; the message includes
305 * more information than just a code; and use of a domain helps prevent
306 * misinterpretation of error codes.
308 * #GError has disadvantages though: it requires a memory allocation, and
309 * formatting the error message string has a performance overhead. This makes it
310 * unsuitable for use in retry loops where errors are a common case, rather than
311 * being unusual. For example, using %G_IO_ERROR_WOULD_BLOCK means hitting these
312 * overheads in the normal control flow. String formatting overhead can be
313 * eliminated by using g_set_error_literal() in some cases.
315 * These performance issues can be compounded if a function wraps the #GErrors
316 * returned by the functions it calls: this multiplies the number of allocations
317 * and string formatting operations. This can be partially mitigated by using
320 * ## Rules for use of #GError # {#gerror-rules}
322 * Summary of rules for use of #GError:
324 * - Do not report programming errors via #GError.
326 * - The last argument of a function that returns an error should
327 * be a location where a #GError can be placed (i.e. `GError **error`).
328 * If #GError is used with varargs, the `GError**` should be the last
329 * argument before the `...`.
331 * - The caller may pass %NULL for the `GError**` if they are not interested
332 * in details of the exact error that occurred.
334 * - If %NULL is passed for the `GError**` argument, then errors should
335 * not be returned to the caller, but your function should still
336 * abort and return if an error occurs. That is, control flow should
337 * not be affected by whether the caller wants to get a #GError.
339 * - If a #GError is reported, then your function by definition had a
340 * fatal failure and did not complete whatever it was supposed to do.
341 * If the failure was not fatal, then you handled it and you should not
342 * report it. If it was fatal, then you must report it and discontinue
343 * whatever you were doing immediately.
345 * - If a #GError is reported, out parameters are not guaranteed to
346 * be set to any defined value.
348 * - A `GError*` must be initialized to %NULL before passing its address
349 * to a function that can report errors.
351 * - #GError structs must not be stack-allocated.
353 * - "Piling up" errors is always a bug. That is, if you assign a
354 * new #GError to a `GError*` that is non-%NULL, thus overwriting
355 * the previous error, it indicates that you should have aborted
356 * the operation instead of continuing. If you were able to continue,
357 * you should have cleared the previous error with g_clear_error().
358 * g_set_error() will complain if you pile up errors.
360 * - By convention, if you return a boolean value indicating success
361 * then %TRUE means success and %FALSE means failure. Avoid creating
362 * functions which have a boolean return value and a #GError parameter,
363 * but where the boolean does something other than signal whether the
364 * #GError is set. Among other problems, it requires C callers to allocate
365 * a temporary error. Instead, provide a `gboolean *` out parameter.
366 * There are functions in GLib itself such as g_key_file_has_key() that
367 * are hard to use because of this. If %FALSE is returned, the error must
368 * be set to a non-%NULL value. One exception to this is that in situations
369 * that are already considered to be undefined behaviour (such as when a
370 * g_return_val_if_fail() check fails), the error need not be set.
371 * Instead of checking separately whether the error is set, callers
372 * should ensure that they do not provoke undefined behaviour, then
373 * assume that the error will be set on failure.
375 * - A %NULL return value is also frequently used to mean that an error
376 * occurred. You should make clear in your documentation whether %NULL
377 * is a valid return value in non-error cases; if %NULL is a valid value,
378 * then users must check whether an error was returned to see if the
379 * function succeeded.
381 * - When implementing a function that can report errors, you may want
382 * to add a check at the top of your function that the error return
383 * location is either %NULL or contains a %NULL error (e.g.
384 * `g_return_if_fail (error == NULL || *error == NULL);`).
386 * ## Extended #GError Domains # {#gerror-extended-domains}
388 * Since GLib 2.68 it is possible to extend the #GError type. This is
389 * done with the G_DEFINE_EXTENDED_ERROR() macro. To create an
390 * extended #GError type do something like this in the header file:
391 * |[<!-- language="C" -->
394 * MY_ERROR_BAD_REQUEST,
396 * #define MY_ERROR (my_error_quark ())
397 * GQuark my_error_quark (void);
399 * my_error_get_parse_error_id (GError *error);
401 * my_error_get_bad_request_details (GError *error);
403 * and in implementation:
404 * |[<!-- language="C" -->
407 * int parse_error_id;
408 * char *bad_request_details;
412 * my_error_private_init (MyErrorPrivate *priv)
414 * priv->parse_error_id = -1;
415 * // No need to set priv->bad_request_details to NULL,
416 * // the struct is initialized with zeros.
420 * my_error_private_copy (const MyErrorPrivate *src_priv, MyErrorPrivate *dest_priv)
422 * dest_priv->parse_error_id = src_priv->parse_error_id;
423 * dest_priv->bad_request_details = g_strdup (src_priv->bad_request_details);
427 * my_error_private_clear (MyErrorPrivate *priv)
429 * g_free (priv->bad_request_details);
432 * // This defines the my_error_get_private and my_error_quark functions.
433 * G_DEFINE_EXTENDED_ERROR (MyError, my_error)
436 * my_error_get_parse_error_id (GError *error)
438 * MyErrorPrivate *priv = my_error_get_private (error);
439 * g_return_val_if_fail (priv != NULL, -1);
440 * return priv->parse_error_id;
444 * my_error_get_bad_request_details (GError *error)
446 * MyErrorPrivate *priv = my_error_get_private (error);
447 * g_return_val_if_fail (priv != NULL, NULL);
448 * g_return_val_if_fail (error->code != MY_ERROR_BAD_REQUEST, NULL);
449 * return priv->bad_request_details;
453 * my_error_set_bad_request (GError **error,
454 * const char *reason,
456 * const char *details)
458 * MyErrorPrivate *priv;
459 * g_set_error (error, MY_ERROR, MY_ERROR_BAD_REQUEST, "Invalid request: %s", reason);
460 * if (error != NULL && *error != NULL)
462 * priv = my_error_get_private (error);
463 * g_return_val_if_fail (priv != NULL, NULL);
464 * priv->parse_error_id = error_id;
465 * priv->bad_request_details = g_strdup (details);
469 * An example of use of the error could be:
470 * |[<!-- language="C" -->
472 * send_request (GBytes *request, GError **error)
474 * ParseFailedStatus *failure = validate_request (request);
475 * if (failure != NULL)
477 * my_error_set_bad_request (error, failure->reason, failure->error_id, failure->details);
478 * parse_failed_status_free (failure);
482 * return send_one (request, error);
486 * Please note that if you are a library author and your library
487 * exposes an existing error domain, then you can't make this error
488 * domain an extended one without breaking ABI. This is because
489 * earlier it was possible to create an error with this error domain
490 * on the stack and then copy it with g_error_copy(). If the new
491 * version of your library makes the error domain an extended one,
492 * then g_error_copy() called by code that allocated the error on the
493 * stack will try to copy more data than it used to, which will lead
494 * to undefined behavior. You must not stack-allocate errors with an
495 * extended error domain, and it is bad practice to stack-allocate any
498 * Extended error domains in unloadable plugins/modules are not
504 #include "gvalgrind.h"
510 #include "glib-init.h"
512 #include "gstrfuncs.h"
513 #include "gtestutils.h"
516 static GRWLock error_domain_global;
517 /* error_domain_ht must be accessed with error_domain_global
520 static GHashTable *error_domain_ht = NULL;
525 error_domain_ht = g_hash_table_new (NULL, NULL);
530 /* private_size is already aligned. */
534 GErrorClearFunc clear;
537 /* Must be called with error_domain_global locked.
539 static inline ErrorDomainInfo *
540 error_domain_lookup (GQuark domain)
542 return g_hash_table_lookup (error_domain_ht,
543 GUINT_TO_POINTER (domain));
546 /* Copied from gtype.c. */
547 #define STRUCT_ALIGNMENT (2 * sizeof (gsize))
548 #define ALIGN_STRUCT(offset) \
549 ((offset + (STRUCT_ALIGNMENT - 1)) & -STRUCT_ALIGNMENT)
552 error_domain_register (GQuark error_quark,
553 gsize error_type_private_size,
554 GErrorInitFunc error_type_init,
555 GErrorCopyFunc error_type_copy,
556 GErrorClearFunc error_type_clear)
558 g_rw_lock_writer_lock (&error_domain_global);
559 if (error_domain_lookup (error_quark) == NULL)
561 ErrorDomainInfo *info = g_new (ErrorDomainInfo, 1);
562 info->private_size = ALIGN_STRUCT (error_type_private_size);
563 info->init = error_type_init;
564 info->copy = error_type_copy;
565 info->clear = error_type_clear;
567 g_hash_table_insert (error_domain_ht,
568 GUINT_TO_POINTER (error_quark),
573 const char *name = g_quark_to_string (error_quark);
575 g_critical ("Attempted to register an extended error domain for %s more than once", name);
577 g_rw_lock_writer_unlock (&error_domain_global);
581 * g_error_domain_register_static:
582 * @error_type_name: static string to create a #GQuark from
583 * @error_type_private_size: size of the private error data in bytes
584 * @error_type_init: function initializing fields of the private error data
585 * @error_type_copy: function copying fields of the private error data
586 * @error_type_clear: function freeing fields of the private error data
588 * This function registers an extended #GError domain.
590 * @error_type_name should not be freed. @error_type_private_size must
593 * @error_type_init receives an initialized #GError and should then initialize
596 * @error_type_copy is a function that receives both original and a copy
597 * #GError and should copy the fields of the private error data. The standard
598 * #GError fields are already handled.
600 * @error_type_clear receives the pointer to the error, and it should free the
601 * fields of the private error data. It should not free the struct itself though.
603 * Normally, it is better to use G_DEFINE_EXTENDED_ERROR(), as it
604 * already takes care of passing valid information to this function.
606 * Returns: #GQuark representing the error domain
610 g_error_domain_register_static (const char *error_type_name,
611 gsize error_type_private_size,
612 GErrorInitFunc error_type_init,
613 GErrorCopyFunc error_type_copy,
614 GErrorClearFunc error_type_clear)
618 g_return_val_if_fail (error_type_name != NULL, 0);
619 g_return_val_if_fail (error_type_private_size > 0, 0);
620 g_return_val_if_fail (error_type_init != NULL, 0);
621 g_return_val_if_fail (error_type_copy != NULL, 0);
622 g_return_val_if_fail (error_type_clear != NULL, 0);
624 error_quark = g_quark_from_static_string (error_type_name);
625 error_domain_register (error_quark,
626 error_type_private_size,
634 * g_error_domain_register:
635 * @error_type_name: string to create a #GQuark from
636 * @error_type_private_size: size of the private error data in bytes
637 * @error_type_init: function initializing fields of the private error data
638 * @error_type_copy: function copying fields of the private error data
639 * @error_type_clear: function freeing fields of the private error data
641 * This function registers an extended #GError domain.
642 * @error_type_name will be duplicated. Otherwise does the same as
643 * g_error_domain_register_static().
645 * Returns: #GQuark representing the error domain
649 g_error_domain_register (const char *error_type_name,
650 gsize error_type_private_size,
651 GErrorInitFunc error_type_init,
652 GErrorCopyFunc error_type_copy,
653 GErrorClearFunc error_type_clear)
657 g_return_val_if_fail (error_type_name != NULL, 0);
658 g_return_val_if_fail (error_type_private_size > 0, 0);
659 g_return_val_if_fail (error_type_init != NULL, 0);
660 g_return_val_if_fail (error_type_copy != NULL, 0);
661 g_return_val_if_fail (error_type_clear != NULL, 0);
663 error_quark = g_quark_from_string (error_type_name);
664 error_domain_register (error_quark,
665 error_type_private_size,
673 g_error_allocate (GQuark domain, ErrorDomainInfo *out_info)
677 ErrorDomainInfo *info;
680 g_rw_lock_reader_lock (&error_domain_global);
681 info = error_domain_lookup (domain);
684 if (out_info != NULL)
686 private_size = info->private_size;
687 g_rw_lock_reader_unlock (&error_domain_global);
691 g_rw_lock_reader_unlock (&error_domain_global);
692 if (out_info != NULL)
693 memset (out_info, 0, sizeof (*out_info));
696 /* See comments in g_type_create_instance in gtype.c to see what
697 * this magic is about.
699 #ifdef ENABLE_VALGRIND
700 if (private_size > 0 && RUNNING_ON_VALGRIND)
702 private_size += ALIGN_STRUCT (1);
703 allocated = g_slice_alloc0 (private_size + sizeof (GError) + sizeof (gpointer));
704 *(gpointer *) (allocated + private_size + sizeof (GError)) = allocated + ALIGN_STRUCT (1);
705 VALGRIND_MALLOCLIKE_BLOCK (allocated + private_size, sizeof (GError) + sizeof (gpointer), 0, TRUE);
706 VALGRIND_MALLOCLIKE_BLOCK (allocated + ALIGN_STRUCT (1), private_size - ALIGN_STRUCT (1), 0, TRUE);
710 allocated = g_slice_alloc0 (private_size + sizeof (GError));
712 error = (GError *) (allocated + private_size);
716 /* This function takes ownership of @message. */
718 g_error_new_steal (GQuark domain,
721 ErrorDomainInfo *out_info)
723 ErrorDomainInfo info;
724 GError *error = g_error_allocate (domain, &info);
726 error->domain = domain;
728 error->message = message;
730 if (info.init != NULL)
732 if (out_info != NULL)
739 * g_error_new_valist:
740 * @domain: error domain
742 * @format: printf()-style format for error message
743 * @args: #va_list of parameters for the message format
745 * Creates a new #GError with the given @domain and @code,
746 * and a message formatted with @format.
748 * Returns: a new #GError
753 g_error_new_valist (GQuark domain,
758 g_return_val_if_fail (format != NULL, NULL);
760 /* Historically, GError allowed this (although it was never meant to work),
761 * and it has significant use in the wild, which g_return_val_if_fail
762 * would break. It should maybe g_return_val_if_fail in GLib 4.
763 * (GNOME#660371, GNOME#560482)
765 g_warn_if_fail (domain != 0);
767 return g_error_new_steal (domain, code, g_strdup_vprintf (format, args), NULL);
772 * @domain: error domain
774 * @format: printf()-style format for error message
775 * @...: parameters for message format
777 * Creates a new #GError with the given @domain and @code,
778 * and a message formatted with @format.
780 * Returns: a new #GError
783 g_error_new (GQuark domain,
791 g_return_val_if_fail (format != NULL, NULL);
792 g_return_val_if_fail (domain != 0, NULL);
794 va_start (args, format);
795 error = g_error_new_valist (domain, code, format, args);
802 * g_error_new_literal:
803 * @domain: error domain
805 * @message: error message
807 * Creates a new #GError; unlike g_error_new(), @message is
808 * not a printf()-style format string. Use this function if
809 * @message contains text you don't have control over,
810 * that could include printf() escape sequences.
812 * Returns: a new #GError
815 g_error_new_literal (GQuark domain,
817 const gchar *message)
819 g_return_val_if_fail (message != NULL, NULL);
820 g_return_val_if_fail (domain != 0, NULL);
822 return g_error_new_steal (domain, code, g_strdup (message), NULL);
829 * Frees a #GError and associated resources.
832 g_error_free (GError *error)
835 ErrorDomainInfo *info;
838 g_return_if_fail (error != NULL);
840 g_rw_lock_reader_lock (&error_domain_global);
841 info = error_domain_lookup (error->domain);
844 GErrorClearFunc clear = info->clear;
846 private_size = info->private_size;
847 g_rw_lock_reader_unlock (&error_domain_global);
852 g_rw_lock_reader_unlock (&error_domain_global);
856 g_free (error->message);
857 allocated = ((guint8 *) error) - private_size;
858 /* See comments in g_type_free_instance in gtype.c to see what this
861 #ifdef ENABLE_VALGRIND
862 if (private_size > 0 && RUNNING_ON_VALGRIND)
864 private_size += ALIGN_STRUCT (1);
865 allocated -= ALIGN_STRUCT (1);
866 *(gpointer *) (allocated + private_size + sizeof (GError)) = NULL;
867 g_slice_free1 (private_size + sizeof (GError) + sizeof (gpointer), allocated);
868 VALGRIND_FREELIKE_BLOCK (allocated + ALIGN_STRUCT (1), 0);
869 VALGRIND_FREELIKE_BLOCK (error, 0);
873 g_slice_free1 (private_size + sizeof (GError), allocated);
880 * Makes a copy of @error.
882 * Returns: a new #GError
885 g_error_copy (const GError *error)
888 ErrorDomainInfo info;
890 g_return_val_if_fail (error != NULL, NULL);
891 g_return_val_if_fail (error->message != NULL, NULL);
893 /* See g_error_new_valist for why this doesn’t return */
894 g_warn_if_fail (error->domain != 0);
896 copy = g_error_new_steal (error->domain,
898 g_strdup (error->message),
900 if (info.copy != NULL)
901 info.copy (error, copy);
908 * @error: (nullable): a #GError
909 * @domain: an error domain
910 * @code: an error code
912 * Returns %TRUE if @error matches @domain and @code, %FALSE
913 * otherwise. In particular, when @error is %NULL, %FALSE will
916 * If @domain contains a `FAILED` (or otherwise generic) error code,
917 * you should generally not check for it explicitly, but should
918 * instead treat any not-explicitly-recognized error code as being
919 * equivalent to the `FAILED` code. This way, if the domain is
920 * extended in the future to provide a more specific error code for
921 * a certain case, your code will still work.
923 * Returns: whether @error has @domain and @code
926 g_error_matches (const GError *error,
931 error->domain == domain &&
935 #define ERROR_OVERWRITTEN_WARNING "GError set over the top of a previous GError or uninitialized memory.\n" \
936 "This indicates a bug in someone's code. You must ensure an error is NULL before it's set.\n" \
937 "The overwriting error message was: %s"
941 * @err: (out callee-allocates) (optional): a return location for a #GError
942 * @domain: error domain
944 * @format: printf()-style format
945 * @...: args for @format
947 * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
948 * must be %NULL. A new #GError is created and assigned to *@err.
951 g_set_error (GError **err,
964 va_start (args, format);
965 new = g_error_new_valist (domain, code, format, args);
972 g_warning (ERROR_OVERWRITTEN_WARNING, new->message);
978 * g_set_error_literal:
979 * @err: (out callee-allocates) (optional): a return location for a #GError
980 * @domain: error domain
982 * @message: error message
984 * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
985 * must be %NULL. A new #GError is created and assigned to *@err.
986 * Unlike g_set_error(), @message is not a printf()-style format string.
987 * Use this function if @message contains text you don't have control over,
988 * that could include printf() escape sequences.
993 g_set_error_literal (GError **err,
996 const gchar *message)
1002 *err = g_error_new_literal (domain, code, message);
1004 g_warning (ERROR_OVERWRITTEN_WARNING, message);
1008 * g_propagate_error:
1009 * @dest: (out callee-allocates) (optional) (nullable): error return location
1010 * @src: (transfer full): error to move into the return location
1012 * If @dest is %NULL, free @src; otherwise, moves @src into *@dest.
1013 * The error variable @dest points to must be %NULL.
1015 * @src must be non-%NULL.
1017 * Note that @src is no longer valid after this call. If you want
1018 * to keep using the same GError*, you need to set it to %NULL
1019 * after calling this function on it.
1022 g_propagate_error (GError **dest,
1025 g_return_if_fail (src != NULL);
1036 g_warning (ERROR_OVERWRITTEN_WARNING, src->message);
1046 * @err: a #GError return location
1048 * If @err or *@err is %NULL, does nothing. Otherwise,
1049 * calls g_error_free() on *@err and sets *@err to %NULL.
1052 g_clear_error (GError **err)
1056 g_error_free (*err);
1063 g_error_add_prefix (gchar **string,
1064 const gchar *format,
1070 prefix = g_strdup_vprintf (format, ap);
1071 oldstring = *string;
1072 *string = g_strconcat (prefix, oldstring, NULL);
1079 * @err: (inout) (optional) (nullable): a return location for a #GError
1080 * @format: printf()-style format string
1081 * @...: arguments to @format
1083 * Formats a string according to @format and prefix it to an existing
1084 * error message. If @err is %NULL (ie: no error variable) then do
1087 * If *@err is %NULL (ie: an error variable is present but there is no
1088 * error condition) then also do nothing.
1093 g_prefix_error (GError **err,
1094 const gchar *format,
1101 va_start (ap, format);
1102 g_error_add_prefix (&(*err)->message, format, ap);
1108 * g_prefix_error_literal:
1109 * @err: (allow-none): a return location for a #GError, or %NULL
1110 * @prefix: string to prefix @err with
1112 * Prefixes @prefix to an existing error message. If @err or *@err is
1113 * %NULL (i.e.: no error variable) then do nothing.
1118 g_prefix_error_literal (GError **err,
1119 const gchar *prefix)
1125 oldstring = (*err)->message;
1126 (*err)->message = g_strconcat (prefix, oldstring, NULL);
1132 * g_propagate_prefixed_error:
1133 * @dest: error return location
1134 * @src: error to move into the return location
1135 * @format: printf()-style format string
1136 * @...: arguments to @format
1138 * If @dest is %NULL, free @src; otherwise, moves @src into *@dest.
1139 * *@dest must be %NULL. After the move, add a prefix as with
1145 g_propagate_prefixed_error (GError **dest,
1147 const gchar *format,
1150 g_propagate_error (dest, src);
1156 g_assert (*dest != NULL);
1157 va_start (ap, format);
1158 g_error_add_prefix (&(*dest)->message, format, ap);