gatomic: Add missing new line in API doc comment
[glib.git] / glib / gerror.c
blob958f776af01cd3034e286c7bc5098ecc0af37ee1
1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
20 * file for a list of people on the GLib Team. See the ChangeLog
21 * files for a list of changes. These files are distributed with
22 * GLib at ftp://ftp.gtk.org/pub/gtk/.
25 /**
26 * SECTION:error_reporting
27 * @Title: Error Reporting
28 * @Short_description: a system for reporting errors
30 * GLib provides a standard method of reporting errors from a called
31 * function to the calling code. (This is the same problem solved by
32 * exceptions in other languages.) It's important to understand that
33 * this method is both a data type (the #GError struct) and a set of
34 * rules. If you use #GError incorrectly, then your code will not
35 * properly interoperate with other code that uses #GError, and users
36 * of your API will probably get confused.
38 * First and foremost: #GError should only be used to report recoverable
39 * runtime errors, never to report programming errors. If the programmer
40 * has screwed up, then you should use g_warning(), g_return_if_fail(),
41 * g_assert(), g_error(), or some similar facility. (Incidentally,
42 * remember that the g_error() function should only be used for
43 * programming errors, it should not be used to print any error
44 * reportable via #GError.)
46 * Examples of recoverable runtime errors are "file not found" or
47 * "failed to parse input." Examples of programming errors are "NULL
48 * passed to strcmp()" or "attempted to free the same pointer twice."
49 * These two kinds of errors are fundamentally different: runtime errors
50 * should be handled or reported to the user, programming errors should
51 * be eliminated by fixing the bug in the program. This is why most
52 * functions in GLib and GTK+ do not use the #GError facility.
54 * Functions that can fail take a return location for a #GError as their
55 * last argument. On error, a new #GError instance will be allocated and
56 * returned to the caller via this argument. For example:
57 * |[<!-- language="C" -->
58 * gboolean g_file_get_contents (const gchar *filename,
59 * gchar **contents,
60 * gsize *length,
61 * GError **error);
62 * ]|
63 * If you pass a non-%NULL value for the `error` argument, it should
64 * point to a location where an error can be placed. For example:
65 * |[<!-- language="C" -->
66 * gchar *contents;
67 * GError *err = NULL;
69 * g_file_get_contents ("foo.txt", &contents, NULL, &err);
70 * g_assert ((contents == NULL && err != NULL) || (contents != NULL && err == NULL));
71 * if (err != NULL)
72 * {
73 * // Report error to user, and free error
74 * g_assert (contents == NULL);
75 * fprintf (stderr, "Unable to read file: %s\n", err->message);
76 * g_error_free (err);
77 * }
78 * else
79 * {
80 * // Use file contents
81 * g_assert (contents != NULL);
82 * }
83 * ]|
84 * Note that `err != NULL` in this example is a reliable indicator
85 * of whether g_file_get_contents() failed. Additionally,
86 * g_file_get_contents() returns a boolean which
87 * indicates whether it was successful.
89 * Because g_file_get_contents() returns %FALSE on failure, if you
90 * are only interested in whether it failed and don't need to display
91 * an error message, you can pass %NULL for the @error argument:
92 * |[<!-- language="C" -->
93 * if (g_file_get_contents ("foo.txt", &contents, NULL, NULL)) // ignore errors
94 * // no error occurred
95 * ;
96 * else
97 * // error
98 * ;
99 * ]|
101 * The #GError object contains three fields: @domain indicates the module
102 * the error-reporting function is located in, @code indicates the specific
103 * error that occurred, and @message is a user-readable error message with
104 * as many details as possible. Several functions are provided to deal
105 * with an error received from a called function: g_error_matches()
106 * returns %TRUE if the error matches a given domain and code,
107 * g_propagate_error() copies an error into an error location (so the
108 * calling function will receive it), and g_clear_error() clears an
109 * error location by freeing the error and resetting the location to
110 * %NULL. To display an error to the user, simply display the @message,
111 * perhaps along with additional context known only to the calling
112 * function (the file being opened, or whatever - though in the
113 * g_file_get_contents() case, the @message already contains a filename).
115 * When implementing a function that can report errors, the basic
116 * tool is g_set_error(). Typically, if a fatal error occurs you
117 * want to g_set_error(), then return immediately. g_set_error()
118 * does nothing if the error location passed to it is %NULL.
119 * Here's an example:
120 * |[<!-- language="C" -->
121 * gint
122 * foo_open_file (GError **error)
124 * gint fd;
126 * fd = open ("file.txt", O_RDONLY);
128 * if (fd < 0)
130 * g_set_error (error,
131 * FOO_ERROR, // error domain
132 * FOO_ERROR_BLAH, // error code
133 * "Failed to open file: %s", // error message format string
134 * g_strerror (errno));
135 * return -1;
137 * else
138 * return fd;
140 * ]|
142 * Things are somewhat more complicated if you yourself call another
143 * function that can report a #GError. If the sub-function indicates
144 * fatal errors in some way other than reporting a #GError, such as
145 * by returning %TRUE on success, you can simply do the following:
146 * |[<!-- language="C" -->
147 * gboolean
148 * my_function_that_can_fail (GError **err)
150 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
152 * if (!sub_function_that_can_fail (err))
154 * // assert that error was set by the sub-function
155 * g_assert (err == NULL || *err != NULL);
156 * return FALSE;
159 * // otherwise continue, no error occurred
160 * g_assert (err == NULL || *err == NULL);
162 * ]|
164 * If the sub-function does not indicate errors other than by
165 * reporting a #GError (or if its return value does not reliably indicate
166 * errors) you need to create a temporary #GError
167 * since the passed-in one may be %NULL. g_propagate_error() is
168 * intended for use in this case.
169 * |[<!-- language="C" -->
170 * gboolean
171 * my_function_that_can_fail (GError **err)
173 * GError *tmp_error;
175 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
177 * tmp_error = NULL;
178 * sub_function_that_can_fail (&tmp_error);
180 * if (tmp_error != NULL)
182 * // store tmp_error in err, if err != NULL,
183 * // otherwise call g_error_free() on tmp_error
184 * g_propagate_error (err, tmp_error);
185 * return FALSE;
188 * // otherwise continue, no error occurred
190 * ]|
192 * Error pileups are always a bug. For example, this code is incorrect:
193 * |[<!-- language="C" -->
194 * gboolean
195 * my_function_that_can_fail (GError **err)
197 * GError *tmp_error;
199 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
201 * tmp_error = NULL;
202 * sub_function_that_can_fail (&tmp_error);
203 * other_function_that_can_fail (&tmp_error);
205 * if (tmp_error != NULL)
207 * g_propagate_error (err, tmp_error);
208 * return FALSE;
211 * ]|
212 * @tmp_error should be checked immediately after sub_function_that_can_fail(),
213 * and either cleared or propagated upward. The rule is: after each error,
214 * you must either handle the error, or return it to the calling function.
216 * Note that passing %NULL for the error location is the equivalent
217 * of handling an error by always doing nothing about it. So the
218 * following code is fine, assuming errors in sub_function_that_can_fail()
219 * are not fatal to my_function_that_can_fail():
220 * |[<!-- language="C" -->
221 * gboolean
222 * my_function_that_can_fail (GError **err)
224 * GError *tmp_error;
226 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
228 * sub_function_that_can_fail (NULL); // ignore errors
230 * tmp_error = NULL;
231 * other_function_that_can_fail (&tmp_error);
233 * if (tmp_error != NULL)
235 * g_propagate_error (err, tmp_error);
236 * return FALSE;
239 * ]|
241 * Note that passing %NULL for the error location ignores errors;
242 * it's equivalent to
243 * `try { sub_function_that_can_fail (); } catch (...) {}`
244 * in C++. It does not mean to leave errors unhandled; it means
245 * to handle them by doing nothing.
247 * Error domains and codes are conventionally named as follows:
249 * - The error domain is called <NAMESPACE>_<MODULE>_ERROR,
250 * for example %G_SPAWN_ERROR or %G_THREAD_ERROR:
251 * |[<!-- language="C" -->
252 * #define G_SPAWN_ERROR g_spawn_error_quark ()
254 * GQuark
255 * g_spawn_error_quark (void)
257 * return g_quark_from_static_string ("g-spawn-error-quark");
259 * ]|
261 * - The quark function for the error domain is called
262 * <namespace>_<module>_error_quark,
263 * for example g_spawn_error_quark() or g_thread_error_quark().
265 * - The error codes are in an enumeration called
266 * <Namespace><Module>Error;
267 * for example, #GThreadError or #GSpawnError.
269 * - Members of the error code enumeration are called
270 * <NAMESPACE>_<MODULE>_ERROR_<CODE>,
271 * for example %G_SPAWN_ERROR_FORK or %G_THREAD_ERROR_AGAIN.
273 * - If there's a "generic" or "unknown" error code for unrecoverable
274 * errors it doesn't make sense to distinguish with specific codes,
275 * it should be called <NAMESPACE>_<MODULE>_ERROR_FAILED,
276 * for example %G_SPAWN_ERROR_FAILED. In the case of error code
277 * enumerations that may be extended in future releases, you should
278 * generally not handle this error code explicitly, but should
279 * instead treat any unrecognized error code as equivalent to
280 * FAILED.
282 * Summary of rules for use of #GError:
284 * - Do not report programming errors via #GError.
286 * - The last argument of a function that returns an error should
287 * be a location where a #GError can be placed (i.e. "#GError** error").
288 * If #GError is used with varargs, the #GError** should be the last
289 * argument before the "...".
291 * - The caller may pass %NULL for the #GError** if they are not interested
292 * in details of the exact error that occurred.
294 * - If %NULL is passed for the #GError** argument, then errors should
295 * not be returned to the caller, but your function should still
296 * abort and return if an error occurs. That is, control flow should
297 * not be affected by whether the caller wants to get a #GError.
299 * - If a #GError is reported, then your function by definition had a
300 * fatal failure and did not complete whatever it was supposed to do.
301 * If the failure was not fatal, then you handled it and you should not
302 * report it. If it was fatal, then you must report it and discontinue
303 * whatever you were doing immediately.
305 * - If a #GError is reported, out parameters are not guaranteed to
306 * be set to any defined value.
308 * - A #GError* must be initialized to %NULL before passing its address
309 * to a function that can report errors.
311 * - "Piling up" errors is always a bug. That is, if you assign a
312 * new #GError to a #GError* that is non-%NULL, thus overwriting
313 * the previous error, it indicates that you should have aborted
314 * the operation instead of continuing. If you were able to continue,
315 * you should have cleared the previous error with g_clear_error().
316 * g_set_error() will complain if you pile up errors.
318 * - By convention, if you return a boolean value indicating success
319 * then %TRUE means success and %FALSE means failure.
320 * <footnote><para>Avoid creating functions which have a boolean
321 * return value and a GError parameter, but where the boolean does
322 * something other than signal whether the GError is set. Among other
323 * problems, it requires C callers to allocate a temporary error. Instead,
324 * provide a "gboolean *" out parameter. There are functions in GLib
325 * itself such as g_key_file_has_key() that are deprecated because of this.
326 * </para></footnote>
327 * If %FALSE is
328 * returned, the error must be set to a non-%NULL value.
329 * <footnote><para>One exception to this is that in situations that are
330 * already considered to be undefined behaviour (such as when a
331 * g_return_val_if_fail() check fails), the error need not be set.
332 * Instead of checking separately whether the error is set, callers
333 * should ensure that they do not provoke undefined behaviour, then
334 * assume that the error will be set on failure.</para></footnote>
336 * - A %NULL return value is also frequently used to mean that an error
337 * occurred. You should make clear in your documentation whether %NULL
338 * is a valid return value in non-error cases; if %NULL is a valid value,
339 * then users must check whether an error was returned to see if the
340 * function succeeded.
342 * - When implementing a function that can report errors, you may want
343 * to add a check at the top of your function that the error return
344 * location is either %NULL or contains a %NULL error (e.g.
345 * `g_return_if_fail (error == NULL || *error == NULL);`).
348 #include "config.h"
350 #include "gerror.h"
352 #include "gslice.h"
353 #include "gstrfuncs.h"
354 #include "gtestutils.h"
357 * g_error_new_valist:
358 * @domain: error domain
359 * @code: error code
360 * @format: printf()-style format for error message
361 * @args: #va_list of parameters for the message format
363 * Creates a new #GError with the given @domain and @code,
364 * and a message formatted with @format.
366 * Returns: a new #GError
368 * Since: 2.22
370 GError*
371 g_error_new_valist (GQuark domain,
372 gint code,
373 const gchar *format,
374 va_list args)
376 GError *error;
378 /* Historically, GError allowed this (although it was never meant to work),
379 * and it has significant use in the wild, which g_return_val_if_fail
380 * would break. It should maybe g_return_val_if_fail in GLib 4.
381 * (GNOME#660371, GNOME#560482)
383 g_warn_if_fail (domain != 0);
384 g_warn_if_fail (format != NULL);
386 error = g_slice_new (GError);
388 error->domain = domain;
389 error->code = code;
390 error->message = g_strdup_vprintf (format, args);
392 return error;
396 * g_error_new:
397 * @domain: error domain
398 * @code: error code
399 * @format: printf()-style format for error message
400 * @...: parameters for message format
402 * Creates a new #GError with the given @domain and @code,
403 * and a message formatted with @format.
405 * Returns: a new #GError
407 GError*
408 g_error_new (GQuark domain,
409 gint code,
410 const gchar *format,
411 ...)
413 GError* error;
414 va_list args;
416 g_return_val_if_fail (format != NULL, NULL);
417 g_return_val_if_fail (domain != 0, NULL);
419 va_start (args, format);
420 error = g_error_new_valist (domain, code, format, args);
421 va_end (args);
423 return error;
427 * g_error_new_literal:
428 * @domain: error domain
429 * @code: error code
430 * @message: error message
432 * Creates a new #GError; unlike g_error_new(), @message is
433 * not a printf()-style format string. Use this function if
434 * @message contains text you don't have control over,
435 * that could include printf() escape sequences.
437 * Returns: a new #GError
439 GError*
440 g_error_new_literal (GQuark domain,
441 gint code,
442 const gchar *message)
444 GError* err;
446 g_return_val_if_fail (message != NULL, NULL);
447 g_return_val_if_fail (domain != 0, NULL);
449 err = g_slice_new (GError);
451 err->domain = domain;
452 err->code = code;
453 err->message = g_strdup (message);
455 return err;
459 * g_error_free:
460 * @error: a #GError
462 * Frees a #GError and associated resources.
464 void
465 g_error_free (GError *error)
467 g_return_if_fail (error != NULL);
469 g_free (error->message);
471 g_slice_free (GError, error);
475 * g_error_copy:
476 * @error: a #GError
478 * Makes a copy of @error.
480 * Returns: a new #GError
482 GError*
483 g_error_copy (const GError *error)
485 GError *copy;
487 g_return_val_if_fail (error != NULL, NULL);
488 /* See g_error_new_valist for why these don't return */
489 g_warn_if_fail (error->domain != 0);
490 g_warn_if_fail (error->message != NULL);
492 copy = g_slice_new (GError);
494 *copy = *error;
496 copy->message = g_strdup (error->message);
498 return copy;
502 * g_error_matches:
503 * @error: (allow-none): a #GError or %NULL
504 * @domain: an error domain
505 * @code: an error code
507 * Returns %TRUE if @error matches @domain and @code, %FALSE
508 * otherwise. In particular, when @error is %NULL, %FALSE will
509 * be returned.
511 * If @domain contains a `FAILED` (or otherwise generic) error code,
512 * you should generally not check for it explicitly, but should
513 * instead treat any not-explicitly-recognized error code as being
514 * equilalent to the `FAILED` code. This way, if the domain is
515 * extended in the future to provide a more specific error code for
516 * a certain case, your code will still work.
518 * Returns: whether @error has @domain and @code
520 gboolean
521 g_error_matches (const GError *error,
522 GQuark domain,
523 gint code)
525 return error &&
526 error->domain == domain &&
527 error->code == code;
530 #define ERROR_OVERWRITTEN_WARNING "GError set over the top of a previous GError or uninitialized memory.\n" \
531 "This indicates a bug in someone's code. You must ensure an error is NULL before it's set.\n" \
532 "The overwriting error message was: %s"
535 * g_set_error:
536 * @err: (allow-none): a return location for a #GError, or %NULL
537 * @domain: error domain
538 * @code: error code
539 * @format: printf()-style format
540 * @...: args for @format
542 * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
543 * must be %NULL. A new #GError is created and assigned to *@err.
545 void
546 g_set_error (GError **err,
547 GQuark domain,
548 gint code,
549 const gchar *format,
550 ...)
552 GError *new;
554 va_list args;
556 if (err == NULL)
557 return;
559 va_start (args, format);
560 new = g_error_new_valist (domain, code, format, args);
561 va_end (args);
563 if (*err == NULL)
564 *err = new;
565 else
567 g_warning (ERROR_OVERWRITTEN_WARNING, new->message);
568 g_error_free (new);
573 * g_set_error_literal:
574 * @err: (allow-none): a return location for a #GError, or %NULL
575 * @domain: error domain
576 * @code: error code
577 * @message: error message
579 * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
580 * must be %NULL. A new #GError is created and assigned to *@err.
581 * Unlike g_set_error(), @message is not a printf()-style format string.
582 * Use this function if @message contains text you don't have control over,
583 * that could include printf() escape sequences.
585 * Since: 2.18
587 void
588 g_set_error_literal (GError **err,
589 GQuark domain,
590 gint code,
591 const gchar *message)
593 if (err == NULL)
594 return;
596 if (*err == NULL)
597 *err = g_error_new_literal (domain, code, message);
598 else
599 g_warning (ERROR_OVERWRITTEN_WARNING, message);
603 * g_propagate_error:
604 * @dest: error return location
605 * @src: error to move into the return location
607 * If @dest is %NULL, free @src; otherwise, moves @src into *@dest.
608 * The error variable @dest points to must be %NULL.
610 * Note that @src is no longer valid after this call. If you want
611 * to keep using the same GError*, you need to set it to %NULL
612 * after calling this function on it.
614 void
615 g_propagate_error (GError **dest,
616 GError *src)
618 g_return_if_fail (src != NULL);
620 if (dest == NULL)
622 if (src)
623 g_error_free (src);
624 return;
626 else
628 if (*dest != NULL)
630 g_warning (ERROR_OVERWRITTEN_WARNING, src->message);
631 g_error_free (src);
633 else
634 *dest = src;
639 * g_clear_error:
640 * @err: a #GError return location
642 * If @err is %NULL, does nothing. If @err is non-%NULL,
643 * calls g_error_free() on *@err and sets *@err to %NULL.
645 void
646 g_clear_error (GError **err)
648 if (err && *err)
650 g_error_free (*err);
651 *err = NULL;
655 G_GNUC_PRINTF(2, 0)
656 static void
657 g_error_add_prefix (gchar **string,
658 const gchar *format,
659 va_list ap)
661 gchar *oldstring;
662 gchar *prefix;
664 prefix = g_strdup_vprintf (format, ap);
665 oldstring = *string;
666 *string = g_strconcat (prefix, oldstring, NULL);
667 g_free (oldstring);
668 g_free (prefix);
672 * g_prefix_error:
673 * @err: (allow-none): a return location for a #GError, or %NULL
674 * @format: printf()-style format string
675 * @...: arguments to @format
677 * Formats a string according to @format and prefix it to an existing
678 * error message. If @err is %NULL (ie: no error variable) then do
679 * nothing.
681 * If *@err is %NULL (ie: an error variable is present but there is no
682 * error condition) then also do nothing. Whether or not it makes sense
683 * to take advantage of this feature is up to you.
685 * Since: 2.16
687 void
688 g_prefix_error (GError **err,
689 const gchar *format,
690 ...)
692 if (err && *err)
694 va_list ap;
696 va_start (ap, format);
697 g_error_add_prefix (&(*err)->message, format, ap);
698 va_end (ap);
703 * g_propagate_prefixed_error:
704 * @dest: error return location
705 * @src: error to move into the return location
706 * @format: printf()-style format string
707 * @...: arguments to @format
709 * If @dest is %NULL, free @src; otherwise, moves @src into *@dest.
710 * *@dest must be %NULL. After the move, add a prefix as with
711 * g_prefix_error().
713 * Since: 2.16
715 void
716 g_propagate_prefixed_error (GError **dest,
717 GError *src,
718 const gchar *format,
719 ...)
721 g_propagate_error (dest, src);
723 if (dest && *dest)
725 va_list ap;
727 va_start (ap, format);
728 g_error_add_prefix (&(*dest)->message, format, ap);
729 va_end (ap);