Partly revert "gio: Add filename type annotations"
[glib.git] / glib / gerror.c
blob380382b332d4ff423857fe2007838ba78a718269
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][gerror-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. In most cases, [using #GError is
37 * preferred over numeric error codes][gerror-comparison], but there are
38 * situations where numeric error codes are useful for performance.
40 * First and foremost: #GError should only be used to report recoverable
41 * runtime errors, never to report programming errors. If the programmer
42 * has screwed up, then you should use g_warning(), g_return_if_fail(),
43 * g_assert(), g_error(), or some similar facility. (Incidentally,
44 * remember that the g_error() function should only be used for
45 * programming errors, it should not be used to print any error
46 * reportable via #GError.)
48 * Examples of recoverable runtime errors are "file not found" or
49 * "failed to parse input." Examples of programming errors are "NULL
50 * passed to strcmp()" or "attempted to free the same pointer twice."
51 * These two kinds of errors are fundamentally different: runtime errors
52 * should be handled or reported to the user, programming errors should
53 * be eliminated by fixing the bug in the program. This is why most
54 * functions in GLib and GTK+ do not use the #GError facility.
56 * Functions that can fail take a return location for a #GError as their
57 * last argument. On error, a new #GError instance will be allocated and
58 * returned to the caller via this argument. For example:
59 * |[<!-- language="C" -->
60 * gboolean g_file_get_contents (const gchar *filename,
61 * gchar **contents,
62 * gsize *length,
63 * GError **error);
64 * ]|
65 * If you pass a non-%NULL value for the `error` argument, it should
66 * point to a location where an error can be placed. For example:
67 * |[<!-- language="C" -->
68 * gchar *contents;
69 * GError *err = NULL;
71 * g_file_get_contents ("foo.txt", &contents, NULL, &err);
72 * g_assert ((contents == NULL && err != NULL) || (contents != NULL && err == NULL));
73 * if (err != NULL)
74 * {
75 * // Report error to user, and free error
76 * g_assert (contents == NULL);
77 * fprintf (stderr, "Unable to read file: %s\n", err->message);
78 * g_error_free (err);
79 * }
80 * else
81 * {
82 * // Use file contents
83 * g_assert (contents != NULL);
84 * }
85 * ]|
86 * Note that `err != NULL` in this example is a reliable indicator
87 * of whether g_file_get_contents() failed. Additionally,
88 * g_file_get_contents() returns a boolean which
89 * indicates whether it was successful.
91 * Because g_file_get_contents() returns %FALSE on failure, if you
92 * are only interested in whether it failed and don't need to display
93 * an error message, you can pass %NULL for the @error argument:
94 * |[<!-- language="C" -->
95 * if (g_file_get_contents ("foo.txt", &contents, NULL, NULL)) // ignore errors
96 * // no error occurred
97 * ;
98 * else
99 * // error
101 * ]|
103 * The #GError object contains three fields: @domain indicates the module
104 * the error-reporting function is located in, @code indicates the specific
105 * error that occurred, and @message is a user-readable error message with
106 * as many details as possible. Several functions are provided to deal
107 * with an error received from a called function: g_error_matches()
108 * returns %TRUE if the error matches a given domain and code,
109 * g_propagate_error() copies an error into an error location (so the
110 * calling function will receive it), and g_clear_error() clears an
111 * error location by freeing the error and resetting the location to
112 * %NULL. To display an error to the user, simply display the @message,
113 * perhaps along with additional context known only to the calling
114 * function (the file being opened, or whatever - though in the
115 * g_file_get_contents() case, the @message already contains a filename).
117 * When implementing a function that can report errors, the basic
118 * tool is g_set_error(). Typically, if a fatal error occurs you
119 * want to g_set_error(), then return immediately. g_set_error()
120 * does nothing if the error location passed to it is %NULL.
121 * Here's an example:
122 * |[<!-- language="C" -->
123 * gint
124 * foo_open_file (GError **error)
126 * gint fd;
128 * fd = open ("file.txt", O_RDONLY);
130 * if (fd < 0)
132 * g_set_error (error,
133 * FOO_ERROR, // error domain
134 * FOO_ERROR_BLAH, // error code
135 * "Failed to open file: %s", // error message format string
136 * g_strerror (errno));
137 * return -1;
139 * else
140 * return fd;
142 * ]|
144 * Things are somewhat more complicated if you yourself call another
145 * function that can report a #GError. If the sub-function indicates
146 * fatal errors in some way other than reporting a #GError, such as
147 * by returning %TRUE on success, you can simply do the following:
148 * |[<!-- language="C" -->
149 * gboolean
150 * my_function_that_can_fail (GError **err)
152 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
154 * if (!sub_function_that_can_fail (err))
156 * // assert that error was set by the sub-function
157 * g_assert (err == NULL || *err != NULL);
158 * return FALSE;
161 * // otherwise continue, no error occurred
162 * g_assert (err == NULL || *err == NULL);
164 * ]|
166 * If the sub-function does not indicate errors other than by
167 * reporting a #GError (or if its return value does not reliably indicate
168 * errors) you need to create a temporary #GError
169 * since the passed-in one may be %NULL. g_propagate_error() is
170 * intended for use in this case.
171 * |[<!-- language="C" -->
172 * gboolean
173 * my_function_that_can_fail (GError **err)
175 * GError *tmp_error;
177 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
179 * tmp_error = NULL;
180 * sub_function_that_can_fail (&tmp_error);
182 * if (tmp_error != NULL)
184 * // store tmp_error in err, if err != NULL,
185 * // otherwise call g_error_free() on tmp_error
186 * g_propagate_error (err, tmp_error);
187 * return FALSE;
190 * // otherwise continue, no error occurred
192 * ]|
194 * Error pileups are always a bug. For example, this code is incorrect:
195 * |[<!-- language="C" -->
196 * gboolean
197 * my_function_that_can_fail (GError **err)
199 * GError *tmp_error;
201 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
203 * tmp_error = NULL;
204 * sub_function_that_can_fail (&tmp_error);
205 * other_function_that_can_fail (&tmp_error);
207 * if (tmp_error != NULL)
209 * g_propagate_error (err, tmp_error);
210 * return FALSE;
213 * ]|
214 * @tmp_error should be checked immediately after sub_function_that_can_fail(),
215 * and either cleared or propagated upward. The rule is: after each error,
216 * you must either handle the error, or return it to the calling function.
218 * Note that passing %NULL for the error location is the equivalent
219 * of handling an error by always doing nothing about it. So the
220 * following code is fine, assuming errors in sub_function_that_can_fail()
221 * are not fatal to my_function_that_can_fail():
222 * |[<!-- language="C" -->
223 * gboolean
224 * my_function_that_can_fail (GError **err)
226 * GError *tmp_error;
228 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
230 * sub_function_that_can_fail (NULL); // ignore errors
232 * tmp_error = NULL;
233 * other_function_that_can_fail (&tmp_error);
235 * if (tmp_error != NULL)
237 * g_propagate_error (err, tmp_error);
238 * return FALSE;
241 * ]|
243 * Note that passing %NULL for the error location ignores errors;
244 * it's equivalent to
245 * `try { sub_function_that_can_fail (); } catch (...) {}`
246 * in C++. It does not mean to leave errors unhandled; it means
247 * to handle them by doing nothing.
249 * Error domains and codes are conventionally named as follows:
251 * - The error domain is called <NAMESPACE>_<MODULE>_ERROR,
252 * for example %G_SPAWN_ERROR or %G_THREAD_ERROR:
253 * |[<!-- language="C" -->
254 * #define G_SPAWN_ERROR g_spawn_error_quark ()
256 * GQuark
257 * g_spawn_error_quark (void)
259 * return g_quark_from_static_string ("g-spawn-error-quark");
261 * ]|
263 * - The quark function for the error domain is called
264 * <namespace>_<module>_error_quark,
265 * for example g_spawn_error_quark() or g_thread_error_quark().
267 * - The error codes are in an enumeration called
268 * <Namespace><Module>Error;
269 * for example, #GThreadError or #GSpawnError.
271 * - Members of the error code enumeration are called
272 * <NAMESPACE>_<MODULE>_ERROR_<CODE>,
273 * for example %G_SPAWN_ERROR_FORK or %G_THREAD_ERROR_AGAIN.
275 * - If there's a "generic" or "unknown" error code for unrecoverable
276 * errors it doesn't make sense to distinguish with specific codes,
277 * it should be called <NAMESPACE>_<MODULE>_ERROR_FAILED,
278 * for example %G_SPAWN_ERROR_FAILED. In the case of error code
279 * enumerations that may be extended in future releases, you should
280 * generally not handle this error code explicitly, but should
281 * instead treat any unrecognized error code as equivalent to
282 * FAILED.
284 * ## Comparison of #GError and traditional error handling # {#gerror-comparison}
286 * #GError has several advantages over traditional numeric error codes:
287 * importantly, tools like
288 * [gobject-introspection](https://developer.gnome.org/gi/stable/) understand
289 * #GErrors and convert them to exceptions in bindings; the message includes
290 * more information than just a code; and use of a domain helps prevent
291 * misinterpretation of error codes.
293 * #GError has disadvantages though: it requires a memory allocation, and
294 * formatting the error message string has a performance overhead. This makes it
295 * unsuitable for use in retry loops where errors are a common case, rather than
296 * being unusual. For example, using %G_IO_ERROR_WOULD_BLOCK means hitting these
297 * overheads in the normal control flow. String formatting overhead can be
298 * eliminated by using g_set_error_literal() in some cases.
300 * These performance issues can be compounded if a function wraps the #GErrors
301 * returned by the functions it calls: this multiplies the number of allocations
302 * and string formatting operations. This can be partially mitigated by using
303 * g_prefix_error().
305 * ## Rules for use of #GError # {#gerror-rules}
307 * Summary of rules for use of #GError:
309 * - Do not report programming errors via #GError.
311 * - The last argument of a function that returns an error should
312 * be a location where a #GError can be placed (i.e. "#GError** error").
313 * If #GError is used with varargs, the #GError** should be the last
314 * argument before the "...".
316 * - The caller may pass %NULL for the #GError** if they are not interested
317 * in details of the exact error that occurred.
319 * - If %NULL is passed for the #GError** argument, then errors should
320 * not be returned to the caller, but your function should still
321 * abort and return if an error occurs. That is, control flow should
322 * not be affected by whether the caller wants to get a #GError.
324 * - If a #GError is reported, then your function by definition had a
325 * fatal failure and did not complete whatever it was supposed to do.
326 * If the failure was not fatal, then you handled it and you should not
327 * report it. If it was fatal, then you must report it and discontinue
328 * whatever you were doing immediately.
330 * - If a #GError is reported, out parameters are not guaranteed to
331 * be set to any defined value.
333 * - A #GError* must be initialized to %NULL before passing its address
334 * to a function that can report errors.
336 * - "Piling up" errors is always a bug. That is, if you assign a
337 * new #GError to a #GError* that is non-%NULL, thus overwriting
338 * the previous error, it indicates that you should have aborted
339 * the operation instead of continuing. If you were able to continue,
340 * you should have cleared the previous error with g_clear_error().
341 * g_set_error() will complain if you pile up errors.
343 * - By convention, if you return a boolean value indicating success
344 * then %TRUE means success and %FALSE means failure. Avoid creating
345 * functions which have a boolean return value and a GError parameter,
346 * but where the boolean does something other than signal whether the
347 * GError is set. Among other problems, it requires C callers to allocate
348 * a temporary error. Instead, provide a "gboolean *" out parameter.
349 * There are functions in GLib itself such as g_key_file_has_key() that
350 * are deprecated because of this. If %FALSE is returned, the error must
351 * be set to a non-%NULL value. One exception to this is that in situations
352 * that are already considered to be undefined behaviour (such as when a
353 * g_return_val_if_fail() check fails), the error need not be set.
354 * Instead of checking separately whether the error is set, callers
355 * should ensure that they do not provoke undefined behaviour, then
356 * assume that the error will be set on failure.
358 * - A %NULL return value is also frequently used to mean that an error
359 * occurred. You should make clear in your documentation whether %NULL
360 * is a valid return value in non-error cases; if %NULL is a valid value,
361 * then users must check whether an error was returned to see if the
362 * function succeeded.
364 * - When implementing a function that can report errors, you may want
365 * to add a check at the top of your function that the error return
366 * location is either %NULL or contains a %NULL error (e.g.
367 * `g_return_if_fail (error == NULL || *error == NULL);`).
370 #include "config.h"
372 #include "gerror.h"
374 #include "gslice.h"
375 #include "gstrfuncs.h"
376 #include "gtestutils.h"
379 * g_error_new_valist:
380 * @domain: error domain
381 * @code: error code
382 * @format: printf()-style format for error message
383 * @args: #va_list of parameters for the message format
385 * Creates a new #GError with the given @domain and @code,
386 * and a message formatted with @format.
388 * Returns: a new #GError
390 * Since: 2.22
392 GError*
393 g_error_new_valist (GQuark domain,
394 gint code,
395 const gchar *format,
396 va_list args)
398 GError *error;
400 /* Historically, GError allowed this (although it was never meant to work),
401 * and it has significant use in the wild, which g_return_val_if_fail
402 * would break. It should maybe g_return_val_if_fail in GLib 4.
403 * (GNOME#660371, GNOME#560482)
405 g_warn_if_fail (domain != 0);
406 g_warn_if_fail (format != NULL);
408 error = g_slice_new (GError);
410 error->domain = domain;
411 error->code = code;
412 error->message = g_strdup_vprintf (format, args);
414 return error;
418 * g_error_new:
419 * @domain: error domain
420 * @code: error code
421 * @format: printf()-style format for error message
422 * @...: parameters for message format
424 * Creates a new #GError with the given @domain and @code,
425 * and a message formatted with @format.
427 * Returns: a new #GError
429 GError*
430 g_error_new (GQuark domain,
431 gint code,
432 const gchar *format,
433 ...)
435 GError* error;
436 va_list args;
438 g_return_val_if_fail (format != NULL, NULL);
439 g_return_val_if_fail (domain != 0, NULL);
441 va_start (args, format);
442 error = g_error_new_valist (domain, code, format, args);
443 va_end (args);
445 return error;
449 * g_error_new_literal:
450 * @domain: error domain
451 * @code: error code
452 * @message: error message
454 * Creates a new #GError; unlike g_error_new(), @message is
455 * not a printf()-style format string. Use this function if
456 * @message contains text you don't have control over,
457 * that could include printf() escape sequences.
459 * Returns: a new #GError
461 GError*
462 g_error_new_literal (GQuark domain,
463 gint code,
464 const gchar *message)
466 GError* err;
468 g_return_val_if_fail (message != NULL, NULL);
469 g_return_val_if_fail (domain != 0, NULL);
471 err = g_slice_new (GError);
473 err->domain = domain;
474 err->code = code;
475 err->message = g_strdup (message);
477 return err;
481 * g_error_free:
482 * @error: a #GError
484 * Frees a #GError and associated resources.
486 void
487 g_error_free (GError *error)
489 g_return_if_fail (error != NULL);
491 g_free (error->message);
493 g_slice_free (GError, error);
497 * g_error_copy:
498 * @error: a #GError
500 * Makes a copy of @error.
502 * Returns: a new #GError
504 GError*
505 g_error_copy (const GError *error)
507 GError *copy;
509 g_return_val_if_fail (error != NULL, NULL);
510 /* See g_error_new_valist for why these don't return */
511 g_warn_if_fail (error->domain != 0);
512 g_warn_if_fail (error->message != NULL);
514 copy = g_slice_new (GError);
516 *copy = *error;
518 copy->message = g_strdup (error->message);
520 return copy;
524 * g_error_matches:
525 * @error: (nullable): a #GError
526 * @domain: an error domain
527 * @code: an error code
529 * Returns %TRUE if @error matches @domain and @code, %FALSE
530 * otherwise. In particular, when @error is %NULL, %FALSE will
531 * be returned.
533 * If @domain contains a `FAILED` (or otherwise generic) error code,
534 * you should generally not check for it explicitly, but should
535 * instead treat any not-explicitly-recognized error code as being
536 * equivalent to the `FAILED` code. This way, if the domain is
537 * extended in the future to provide a more specific error code for
538 * a certain case, your code will still work.
540 * Returns: whether @error has @domain and @code
542 gboolean
543 g_error_matches (const GError *error,
544 GQuark domain,
545 gint code)
547 return error &&
548 error->domain == domain &&
549 error->code == code;
552 #define ERROR_OVERWRITTEN_WARNING "GError set over the top of a previous GError or uninitialized memory.\n" \
553 "This indicates a bug in someone's code. You must ensure an error is NULL before it's set.\n" \
554 "The overwriting error message was: %s"
557 * g_set_error:
558 * @err: (out callee-allocates) (optional): a return location for a #GError
559 * @domain: error domain
560 * @code: error code
561 * @format: printf()-style format
562 * @...: args for @format
564 * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
565 * must be %NULL. A new #GError is created and assigned to *@err.
567 void
568 g_set_error (GError **err,
569 GQuark domain,
570 gint code,
571 const gchar *format,
572 ...)
574 GError *new;
576 va_list args;
578 if (err == NULL)
579 return;
581 va_start (args, format);
582 new = g_error_new_valist (domain, code, format, args);
583 va_end (args);
585 if (*err == NULL)
586 *err = new;
587 else
589 g_warning (ERROR_OVERWRITTEN_WARNING, new->message);
590 g_error_free (new);
595 * g_set_error_literal:
596 * @err: (out callee-allocates) (optional): a return location for a #GError
597 * @domain: error domain
598 * @code: error code
599 * @message: error message
601 * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
602 * must be %NULL. A new #GError is created and assigned to *@err.
603 * Unlike g_set_error(), @message is not a printf()-style format string.
604 * Use this function if @message contains text you don't have control over,
605 * that could include printf() escape sequences.
607 * Since: 2.18
609 void
610 g_set_error_literal (GError **err,
611 GQuark domain,
612 gint code,
613 const gchar *message)
615 if (err == NULL)
616 return;
618 if (*err == NULL)
619 *err = g_error_new_literal (domain, code, message);
620 else
621 g_warning (ERROR_OVERWRITTEN_WARNING, message);
625 * g_propagate_error:
626 * @dest: (out callee-allocates) (optional) (nullable): error return location
627 * @src: (transfer full): error to move into the return location
629 * If @dest is %NULL, free @src; otherwise, moves @src into *@dest.
630 * The error variable @dest points to must be %NULL.
632 * @src must be non-%NULL.
634 * Note that @src is no longer valid after this call. If you want
635 * to keep using the same GError*, you need to set it to %NULL
636 * after calling this function on it.
638 void
639 g_propagate_error (GError **dest,
640 GError *src)
642 g_return_if_fail (src != NULL);
644 if (dest == NULL)
646 if (src)
647 g_error_free (src);
648 return;
650 else
652 if (*dest != NULL)
654 g_warning (ERROR_OVERWRITTEN_WARNING, src->message);
655 g_error_free (src);
657 else
658 *dest = src;
663 * g_clear_error:
664 * @err: a #GError return location
666 * If @err or *@err is %NULL, does nothing. Otherwise,
667 * calls g_error_free() on *@err and sets *@err to %NULL.
669 void
670 g_clear_error (GError **err)
672 if (err && *err)
674 g_error_free (*err);
675 *err = NULL;
679 G_GNUC_PRINTF(2, 0)
680 static void
681 g_error_add_prefix (gchar **string,
682 const gchar *format,
683 va_list ap)
685 gchar *oldstring;
686 gchar *prefix;
688 prefix = g_strdup_vprintf (format, ap);
689 oldstring = *string;
690 *string = g_strconcat (prefix, oldstring, NULL);
691 g_free (oldstring);
692 g_free (prefix);
696 * g_prefix_error:
697 * @err: (inout) (optional) (nullable): a return location for a #GError
698 * @format: printf()-style format string
699 * @...: arguments to @format
701 * Formats a string according to @format and prefix it to an existing
702 * error message. If @err is %NULL (ie: no error variable) then do
703 * nothing.
705 * If *@err is %NULL (ie: an error variable is present but there is no
706 * error condition) then also do nothing. Whether or not it makes sense
707 * to take advantage of this feature is up to you.
709 * Since: 2.16
711 void
712 g_prefix_error (GError **err,
713 const gchar *format,
714 ...)
716 if (err && *err)
718 va_list ap;
720 va_start (ap, format);
721 g_error_add_prefix (&(*err)->message, format, ap);
722 va_end (ap);
727 * g_propagate_prefixed_error:
728 * @dest: error return location
729 * @src: error to move into the return location
730 * @format: printf()-style format string
731 * @...: arguments to @format
733 * If @dest is %NULL, free @src; otherwise, moves @src into *@dest.
734 * *@dest must be %NULL. After the move, add a prefix as with
735 * g_prefix_error().
737 * Since: 2.16
739 void
740 g_propagate_prefixed_error (GError **dest,
741 GError *src,
742 const gchar *format,
743 ...)
745 g_propagate_error (dest, src);
747 if (dest && *dest)
749 va_list ap;
751 va_start (ap, format);
752 g_error_add_prefix (&(*dest)->message, format, ap);
753 va_end (ap);