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/.
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. For example:
56 * |[<!-- language="C" -->
57 * gboolean g_file_get_contents (const gchar *filename,
62 * If you pass a non-%NULL value for the `error` argument, it should
63 * point to a location where an error can be placed. For example:
64 * |[<!-- language="C" -->
68 * g_file_get_contents ("foo.txt", &contents, NULL, &err);
69 * g_assert ((contents == NULL && err != NULL) || (contents != NULL && err == NULL));
72 * /* Report error to user, and free error */
73 * g_assert (contents == NULL);
74 * fprintf (stderr, "Unable to read file: %s\n", err->message);
79 * /* Use file contents */
80 * g_assert (contents != NULL);
83 * Note that `err != NULL` in this example is a reliable indicator
84 * of whether g_file_get_contents() failed. Additionally,
85 * g_file_get_contents() returns a boolean which
86 * indicates whether it was successful.
88 * Because g_file_get_contents() returns %FALSE on failure, if you
89 * are only interested in whether it failed and don't need to display
90 * an error message, you can pass %NULL for the @error argument:
91 * |[<!-- language="C" -->
92 * if (g_file_get_contents ("foo.txt", &contents, NULL, NULL)) /* ignore errors */
93 * /* no error occurred */ ;
95 * /* error */ ;
98 * The #GError object contains three fields: @domain indicates the module
99 * the error-reporting function is located in, @code indicates the specific
100 * error that occurred, and @message is a user-readable error message with
101 * as many details as possible. Several functions are provided to deal
102 * with an error received from a called function: g_error_matches()
103 * returns %TRUE if the error matches a given domain and code,
104 * g_propagate_error() copies an error into an error location (so the
105 * calling function will receive it), and g_clear_error() clears an
106 * error location by freeing the error and resetting the location to
107 * %NULL. To display an error to the user, simply display the @message,
108 * perhaps along with additional context known only to the calling
109 * function (the file being opened, or whatever - though in the
110 * g_file_get_contents() case, the @message already contains a filename).
112 * When implementing a function that can report errors, the basic
113 * tool is g_set_error(). Typically, if a fatal error occurs you
114 * want to g_set_error(), then return immediately. g_set_error()
115 * does nothing if the error location passed to it is %NULL.
117 * |[<!-- language="C" -->
119 * foo_open_file (GError **error)
123 * fd = open ("file.txt", O_RDONLY);
127 * g_set_error (error,
128 * FOO_ERROR, /* error domain */
129 * FOO_ERROR_BLAH, /* error code */
130 * "Failed to open file: %s", /* error message format string */
131 * g_strerror (errno));
139 * Things are somewhat more complicated if you yourself call another
140 * function that can report a #GError. If the sub-function indicates
141 * fatal errors in some way other than reporting a #GError, such as
142 * by returning %TRUE on success, you can simply do the following:
143 * |[<!-- language="C" -->
145 * my_function_that_can_fail (GError **err)
147 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
149 * if (!sub_function_that_can_fail (err))
151 * /* assert that error was set by the sub-function */
152 * g_assert (err == NULL || *err != NULL);
156 * /* otherwise continue, no error occurred */
157 * g_assert (err == NULL || *err == NULL);
161 * If the sub-function does not indicate errors other than by
162 * reporting a #GError, you need to create a temporary #GError
163 * since the passed-in one may be %NULL. g_propagate_error() is
164 * intended for use in this case.
165 * |[<!-- language="C" -->
167 * my_function_that_can_fail (GError **err)
171 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
174 * sub_function_that_can_fail (&tmp_error);
176 * if (tmp_error != NULL)
178 * /* store tmp_error in err, if err != NULL,
179 * * otherwise call g_error_free() on tmp_error
181 * g_propagate_error (err, tmp_error);
185 * /* otherwise continue, no error occurred */
189 * Error pileups are always a bug. For example, this code is incorrect:
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);
200 * other_function_that_can_fail (&tmp_error);
202 * if (tmp_error != NULL)
204 * g_propagate_error (err, tmp_error);
209 * @tmp_error should be checked immediately after sub_function_that_can_fail(),
210 * and either cleared or propagated upward. The rule is: after each error,
211 * you must either handle the error, or return it to the calling function.
213 * Note that passing %NULL for the error location is the equivalent
214 * of handling an error by always doing nothing about it. So the
215 * following code is fine, assuming errors in sub_function_that_can_fail()
216 * are not fatal to my_function_that_can_fail():
217 * |[<!-- language="C" -->
219 * my_function_that_can_fail (GError **err)
223 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
225 * sub_function_that_can_fail (NULL); /* ignore errors */
228 * other_function_that_can_fail (&tmp_error);
230 * if (tmp_error != NULL)
232 * g_propagate_error (err, tmp_error);
238 * Note that passing %NULL for the error location ignores errors;
240 * `try { sub_function_that_can_fail (); } catch (...) {}`
241 * in C++. It does not mean to leave errors unhandled; it means
242 * to handle them by doing nothing.
244 * Error domains and codes are conventionally named as follows:
246 * - The error domain is called <NAMESPACE>_<MODULE>_ERROR,
247 * for example %G_SPAWN_ERROR or %G_THREAD_ERROR:
248 * |[<!-- language="C" -->
249 * #define G_SPAWN_ERROR g_spawn_error_quark ()
252 * g_spawn_error_quark (void)
254 * return g_quark_from_static_string ("g-spawn-error-quark");
258 * - The quark function for the error domain is called
259 * <namespace>_<module>_error_quark,
260 * for example g_spawn_error_quark() or g_thread_error_quark().
262 * - The error codes are in an enumeration called
263 * <Namespace><Module>Error;
264 * for example, #GThreadError or #GSpawnError.
266 * - Members of the error code enumeration are called
267 * <NAMESPACE>_<MODULE>_ERROR_<CODE>,
268 * for example %G_SPAWN_ERROR_FORK or %G_THREAD_ERROR_AGAIN.
270 * - If there's a "generic" or "unknown" error code for unrecoverable
271 * errors it doesn't make sense to distinguish with specific codes,
272 * it should be called <NAMESPACE>_<MODULE>_ERROR_FAILED,
273 * for example %G_SPAWN_ERROR_FAILED.
275 * Summary of rules for use of #GError:
277 * - Do not report programming errors via #GError.
279 * - The last argument of a function that returns an error should
280 * be a location where a #GError can be placed (i.e. "#GError** error").
281 * If #GError is used with varargs, the #GError** should be the last
282 * argument before the "...".
284 * - The caller may pass %NULL for the #GError** if they are not interested
285 * in details of the exact error that occurred.
287 * - If %NULL is passed for the #GError** argument, then errors should
288 * not be returned to the caller, but your function should still
289 * abort and return if an error occurs. That is, control flow should
290 * not be affected by whether the caller wants to get a #GError.
292 * - If a #GError is reported, then your function by definition had a
293 * fatal failure and did not complete whatever it was supposed to do.
294 * If the failure was not fatal, then you handled it and you should not
295 * report it. If it was fatal, then you must report it and discontinue
296 * whatever you were doing immediately.
298 * - If a #GError is reported, out parameters are not guaranteed to
299 * be set to any defined value.
301 * - A #GError* must be initialized to %NULL before passing its address
302 * to a function that can report errors.
304 * - "Piling up" errors is always a bug. That is, if you assign a
305 * new #GError to a #GError* that is non-%NULL, thus overwriting
306 * the previous error, it indicates that you should have aborted
307 * the operation instead of continuing. If you were able to continue,
308 * you should have cleared the previous error with g_clear_error().
309 * g_set_error() will complain if you pile up errors.
311 * - By convention, if you return a boolean value indicating success
312 * then %TRUE means success and %FALSE means failure.
313 * <footnote><para>Avoid creating functions which have a boolean
314 * return value and a GError parameter, but where the boolean does
315 * something other than signal whether the GError is set. Among other
316 * problems, it requires C callers to allocate a temporary error. Instead,
317 * provide a "gboolean *" out parameter. There are functions in GLib
318 * itself such as g_key_file_has_key() that are deprecated because of this.
321 * returned, the error must be set to a non-%NULL value.
322 * <footnote><para>One exception to this is that in situations that are
323 * already considered to be undefined behaviour (such as when a
324 * g_return_val_if_fail() check fails), the error need not be set.
325 * Instead of checking separately whether the error is set, callers
326 * should ensure that they do not provoke undefined behaviour, then
327 * assume that the error will be set on failure.</para></footnote>
329 * - A %NULL return value is also frequently used to mean that an error
330 * occurred. You should make clear in your documentation whether %NULL
331 * is a valid return value in non-error cases; if %NULL is a valid value,
332 * then users must check whether an error was returned to see if the
333 * function succeeded.
335 * - When implementing a function that can report errors, you may want
336 * to add a check at the top of your function that the error return
337 * location is either %NULL or contains a %NULL error (e.g.
338 * `g_return_if_fail (error == NULL || *error == NULL);`).
346 #include "gstrfuncs.h"
347 #include "gtestutils.h"
350 * g_error_new_valist:
351 * @domain: error domain
353 * @format: printf()-style format for error message
354 * @args: #va_list of parameters for the message format
356 * Creates a new #GError with the given @domain and @code,
357 * and a message formatted with @format.
359 * Returns: a new #GError
364 g_error_new_valist (GQuark domain,
371 /* Historically, GError allowed this (although it was never meant to work),
372 * and it has significant use in the wild, which g_return_val_if_fail
373 * would break. It should maybe g_return_val_if_fail in GLib 4.
374 * (GNOME#660371, GNOME#560482)
376 g_warn_if_fail (domain != 0);
377 g_warn_if_fail (format != NULL);
379 error = g_slice_new (GError);
381 error->domain = domain;
383 error->message = g_strdup_vprintf (format, args);
390 * @domain: error domain
392 * @format: printf()-style format for error message
393 * @...: parameters for message format
395 * Creates a new #GError with the given @domain and @code,
396 * and a message formatted with @format.
398 * Return value: a new #GError
401 g_error_new (GQuark domain,
409 g_return_val_if_fail (format != NULL, NULL);
410 g_return_val_if_fail (domain != 0, NULL);
412 va_start (args, format);
413 error = g_error_new_valist (domain, code, format, args);
420 * g_error_new_literal:
421 * @domain: error domain
423 * @message: error message
425 * Creates a new #GError; unlike g_error_new(), @message is
426 * not a printf()-style format string. Use this function if
427 * @message contains text you don't have control over,
428 * that could include printf() escape sequences.
430 * Return value: a new #GError
433 g_error_new_literal (GQuark domain,
435 const gchar *message)
439 g_return_val_if_fail (message != NULL, NULL);
440 g_return_val_if_fail (domain != 0, NULL);
442 err = g_slice_new (GError);
444 err->domain = domain;
446 err->message = g_strdup (message);
455 * Frees a #GError and associated resources.
458 g_error_free (GError *error)
460 g_return_if_fail (error != NULL);
462 g_free (error->message);
464 g_slice_free (GError, error);
471 * Makes a copy of @error.
473 * Return value: a new #GError
476 g_error_copy (const GError *error)
480 g_return_val_if_fail (error != NULL, NULL);
481 /* See g_error_new_valist for why these don't return */
482 g_warn_if_fail (error->domain != 0);
483 g_warn_if_fail (error->message != NULL);
485 copy = g_slice_new (GError);
489 copy->message = g_strdup (error->message);
496 * @error: (allow-none): a #GError or %NULL
497 * @domain: an error domain
498 * @code: an error code
500 * Returns %TRUE if @error matches @domain and @code, %FALSE
501 * otherwise. In particular, when @error is %NULL, %FALSE will
504 * Return value: whether @error has @domain and @code
507 g_error_matches (const GError *error,
512 error->domain == domain &&
516 #define ERROR_OVERWRITTEN_WARNING "GError set over the top of a previous GError or uninitialized memory.\n" \
517 "This indicates a bug in someone's code. You must ensure an error is NULL before it's set.\n" \
518 "The overwriting error message was: %s"
522 * @err: (allow-none): a return location for a #GError, or %NULL
523 * @domain: error domain
525 * @format: printf()-style format
526 * @...: args for @format
528 * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
529 * must be %NULL. A new #GError is created and assigned to *@err.
532 g_set_error (GError **err,
545 va_start (args, format);
546 new = g_error_new_valist (domain, code, format, args);
553 g_warning (ERROR_OVERWRITTEN_WARNING, new->message);
559 * g_set_error_literal:
560 * @err: (allow-none): a return location for a #GError, or %NULL
561 * @domain: error domain
563 * @message: error message
565 * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
566 * must be %NULL. A new #GError is created and assigned to *@err.
567 * Unlike g_set_error(), @message is not a printf()-style format string.
568 * Use this function if @message contains text you don't have control over,
569 * that could include printf() escape sequences.
574 g_set_error_literal (GError **err,
577 const gchar *message)
583 *err = g_error_new_literal (domain, code, message);
585 g_warning (ERROR_OVERWRITTEN_WARNING, message);
590 * @dest: error return location
591 * @src: error to move into the return location
593 * If @dest is %NULL, free @src; otherwise, moves @src into *@dest.
594 * The error variable @dest points to must be %NULL.
597 g_propagate_error (GError **dest,
600 g_return_if_fail (src != NULL);
612 g_warning (ERROR_OVERWRITTEN_WARNING, src->message);
622 * @err: a #GError return location
624 * If @err is %NULL, does nothing. If @err is non-%NULL,
625 * calls g_error_free() on *@err and sets *@err to %NULL.
628 g_clear_error (GError **err)
639 g_error_add_prefix (gchar **string,
646 prefix = g_strdup_vprintf (format, ap);
648 *string = g_strconcat (prefix, oldstring, NULL);
655 * @err: (allow-none): a return location for a #GError, or %NULL
656 * @format: printf()-style format string
657 * @...: arguments to @format
659 * Formats a string according to @format and prefix it to an existing
660 * error message. If @err is %NULL (ie: no error variable) then do
663 * If *@err is %NULL (ie: an error variable is present but there is no
664 * error condition) then also do nothing. Whether or not it makes sense
665 * to take advantage of this feature is up to you.
670 g_prefix_error (GError **err,
678 va_start (ap, format);
679 g_error_add_prefix (&(*err)->message, format, ap);
685 * g_propagate_prefixed_error:
686 * @dest: error return location
687 * @src: error to move into the return location
688 * @format: printf()-style format string
689 * @...: arguments to @format
691 * If @dest is %NULL, free @src; otherwise, moves @src into *@dest.
692 * *@dest must be %NULL. After the move, add a prefix as with
698 g_propagate_prefixed_error (GError **dest,
703 g_propagate_error (dest, src);
709 va_start (ap, format);
710 g_error_add_prefix (&(*dest)->message, format, ap);