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 <emphasis>data type</emphasis> (the #GError
34 * object) and a <emphasis>set of rules.</emphasis> If you use #GError
35 * incorrectly, then your code will not properly interoperate with other
36 * code that uses #GError, and users of your API will probably get confused.
38 * First and foremost: <emphasis>#GError should only be used to report
39 * recoverable runtime errors, never to report programming
40 * errors.</emphasis> If the programmer has screwed up, then you should
41 * use g_warning(), g_return_if_fail(), g_assert(), g_error(), or some
42 * similar facility. (Incidentally, remember that the g_error() function
43 * should <emphasis>only</emphasis> be used for programming errors, it
44 * should not be used to print any error 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:
57 * gboolean g_file_get_contents (const gchar *filename,
62 * If you pass a non-%NULL value for the <literal>error</literal>
63 * argument, it should point to a location where an error can be placed.
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 <literal>err != NULL</literal> in this example is a
84 * <emphasis>reliable</emphasis> indicator of whether
85 * g_file_get_contents() failed. Additionally, g_file_get_contents()
86 * returns a boolean which 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 <literal>error</literal>
93 * if (g_file_get_contents ("foo.txt", &contents, NULL, NULL)) /* ignore errors */
94 * /* no error occurred */ ;
96 * /* error */ ;
99 * The #GError object contains three fields: <literal>domain</literal>
100 * indicates the module the error-reporting function is located in,
101 * <literal>code</literal> indicates the specific error that occurred,
102 * and <literal>message</literal> is a user-readable error message with
103 * as many details as possible. Several functions are provided to deal
104 * with an error received from a called function: g_error_matches()
105 * returns %TRUE if the error matches a given domain and code,
106 * g_propagate_error() copies an error into an error location (so the
107 * calling function will receive it), and g_clear_error() clears an
108 * error location by freeing the error and resetting the location to
109 * %NULL. To display an error to the user, simply display
110 * <literal>error->message</literal>, perhaps along with additional
111 * context known only to the calling function (the file being opened,
112 * or whatever -- though in the g_file_get_contents() case,
113 * <literal>error->message</literal> 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.
122 * foo_open_file (GError **error)
126 * fd = open ("file.txt", O_RDONLY);
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));
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:
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);
159 * /* otherwise continue, no error occurred */
160 * g_assert (err == NULL || *err == NULL);
164 * If the sub-function does not indicate errors other than by
165 * reporting a #GError, you need to create a temporary #GError
166 * since the passed-in one may be %NULL. g_propagate_error() is
167 * intended for use in this case.
170 * my_function_that_can_fail (GError **err)
174 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
177 * sub_function_that_can_fail (&tmp_error);
179 * if (tmp_error != NULL)
181 * /* store tmp_error in err, if err != NULL,
182 * * otherwise call g_error_free() on tmp_error
184 * g_propagate_error (err, tmp_error);
188 * /* otherwise continue, no error occurred */
192 * Error pileups are always a bug. For example, this code is incorrect:
195 * my_function_that_can_fail (GError **err)
199 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
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);
212 * <literal>tmp_error</literal> should be checked immediately after
213 * sub_function_that_can_fail(), and either cleared or propagated
214 * upward. The rule is: <emphasis>after each error, you must either
215 * handle the error, or return it to the calling function</emphasis>.
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():
222 * my_function_that_can_fail (GError **err)
226 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
228 * sub_function_that_can_fail (NULL); /* ignore errors */
231 * other_function_that_can_fail (&tmp_error);
233 * if (tmp_error != NULL)
235 * g_propagate_error (err, tmp_error);
241 * Note that passing %NULL for the error location
242 * <emphasis>ignores</emphasis> errors; it's equivalent to
243 * <literal>try { sub_function_that_can_fail (); } catch (...) {}</literal>
244 * in C++. It does <emphasis>not</emphasis> mean to leave errors
245 * unhandled; it means to handle them by doing nothing.
247 * Error domains and codes are conventionally named as follows:
250 * The error domain is called
251 * <literal><NAMESPACE>_<MODULE>_ERROR</literal>,
252 * for example %G_SPAWN_ERROR or %G_THREAD_ERROR:
254 * #define G_SPAWN_ERROR g_spawn_error_quark ()
257 * g_spawn_error_quark (void)
259 * return g_quark_from_static_string ("g-spawn-error-quark");
264 * The quark function for the error domain is called
265 * <literal><namespace>_<module>_error_quark</literal>,
266 * for example g_spawn_error_quark() or g_thread_error_quark().
269 * The error codes are in an enumeration called
270 * <literal><Namespace><Module>Error</literal>;
271 * for example,#GThreadError or #GSpawnError.
274 * Members of the error code enumeration are called
275 * <literal><NAMESPACE>_<MODULE>_ERROR_<CODE></literal>,
276 * for example %G_SPAWN_ERROR_FORK or %G_THREAD_ERROR_AGAIN.
279 * If there's a "generic" or "unknown" error code for unrecoverable
280 * errors it doesn't make sense to distinguish with specific codes,
281 * it should be called <literal><NAMESPACE>_<MODULE>_ERROR_FAILED</literal>,
282 * for example %G_SPAWN_ERROR_FAILED.
286 * Summary of rules for use of #GError:
289 * Do not report programming errors via #GError.
292 * The last argument of a function that returns an error should
293 * be a location where a #GError can be placed (i.e. "#GError** error").
294 * If #GError is used with varargs, the #GError** should be the last
295 * argument before the "...".
298 * The caller may pass %NULL for the #GError** if they are not interested
299 * in details of the exact error that occurred.
302 * If %NULL is passed for the #GError** argument, then errors should
303 * not be returned to the caller, but your function should still
304 * abort and return if an error occurs. That is, control flow should
305 * not be affected by whether the caller wants to get a #GError.
308 * If a #GError is reported, then your function by definition
309 * <emphasis>had a fatal failure and did not complete whatever
310 * it was supposed to do</emphasis>. If the failure was not fatal,
311 * then you handled it and you should not report it. If it was fatal,
312 * then you must report it and discontinue whatever you were doing
316 * If a #GError is reported, out parameters are not guaranteed to
317 * be set to any defined value.
320 * A #GError* must be initialized to %NULL before passing its address
321 * to a function that can report errors.
324 * "Piling up" errors is always a bug. That is, if you assign a
325 * new #GError to a #GError* that is non-%NULL, thus overwriting
326 * the previous error, it indicates that you should have aborted
327 * the operation instead of continuing. If you were able to continue,
328 * you should have cleared the previous error with g_clear_error().
329 * g_set_error() will complain if you pile up errors.
332 * By convention, if you return a boolean value indicating success
333 * then %TRUE means success and %FALSE means failure. If %FALSE is
334 * returned, the error <emphasis>must</emphasis> be set to a non-%NULL
338 * A %NULL return value is also frequently used to mean that an error
339 * occurred. You should make clear in your documentation whether %NULL
340 * is a valid return value in non-error cases; if %NULL is a valid value,
341 * then users must check whether an error was returned to see if the
342 * function succeeded.
345 * When implementing a function that can report errors, you may want
346 * to add a check at the top of your function that the error return
347 * location is either %NULL or contains a %NULL error (e.g.
348 * <literal>g_return_if_fail (error == NULL || *error == NULL);</literal>).
358 #include "gstrfuncs.h"
359 #include "gtestutils.h"
362 * g_error_new_valist:
363 * @domain: error domain
365 * @format: printf()-style format for error message
366 * @args: #va_list of parameters for the message format
368 * Creates a new #GError with the given @domain and @code,
369 * and a message formatted with @format.
371 * Returns: a new #GError
376 g_error_new_valist (GQuark domain,
383 /* Historically, GError allowed this (although it was never meant to work),
384 * and it has significant use in the wild, which g_return_val_if_fail
385 * would break. It should maybe g_return_val_if_fail in GLib 4.
386 * (GNOME#660371, GNOME#560482)
388 g_warn_if_fail (domain != 0);
389 g_warn_if_fail (format != NULL);
391 error = g_slice_new (GError);
393 error->domain = domain;
395 error->message = g_strdup_vprintf (format, args);
402 * @domain: error domain
404 * @format: printf()-style format for error message
405 * @...: parameters for message format
407 * Creates a new #GError with the given @domain and @code,
408 * and a message formatted with @format.
410 * Return value: a new #GError
413 g_error_new (GQuark domain,
421 g_return_val_if_fail (format != NULL, NULL);
422 g_return_val_if_fail (domain != 0, NULL);
424 va_start (args, format);
425 error = g_error_new_valist (domain, code, format, args);
432 * g_error_new_literal:
433 * @domain: error domain
435 * @message: error message
437 * Creates a new #GError; unlike g_error_new(), @message is
438 * not a printf()-style format string. Use this function if
439 * @message contains text you don't have control over,
440 * that could include printf() escape sequences.
442 * Return value: a new #GError
445 g_error_new_literal (GQuark domain,
447 const gchar *message)
451 g_return_val_if_fail (message != NULL, NULL);
452 g_return_val_if_fail (domain != 0, NULL);
454 err = g_slice_new (GError);
456 err->domain = domain;
458 err->message = g_strdup (message);
467 * Frees a #GError and associated resources.
470 g_error_free (GError *error)
472 g_return_if_fail (error != NULL);
474 g_free (error->message);
476 g_slice_free (GError, error);
483 * Makes a copy of @error.
485 * Return value: a new #GError
488 g_error_copy (const GError *error)
492 g_return_val_if_fail (error != NULL, NULL);
493 /* See g_error_new_valist for why these don't return */
494 g_warn_if_fail (error->domain != 0);
495 g_warn_if_fail (error->message != NULL);
497 copy = g_slice_new (GError);
501 copy->message = g_strdup (error->message);
508 * @error: (allow-none): a #GError or %NULL
509 * @domain: an error domain
510 * @code: an error code
512 * Returns %TRUE if @error matches @domain and @code, %FALSE
513 * otherwise. In particular, when @error is %NULL, %FALSE will
516 * Return value: whether @error has @domain and @code
519 g_error_matches (const GError *error,
524 error->domain == domain &&
528 #define ERROR_OVERWRITTEN_WARNING "GError set over the top of a previous GError or uninitialized memory.\n" \
529 "This indicates a bug in someone's code. You must ensure an error is NULL before it's set.\n" \
530 "The overwriting error message was: %s"
534 * @err: (allow-none): a return location for a #GError, or %NULL
535 * @domain: error domain
537 * @format: printf()-style format
538 * @...: args for @format
540 * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
541 * must be %NULL. A new #GError is created and assigned to *@err.
544 g_set_error (GError **err,
557 va_start (args, format);
558 new = g_error_new_valist (domain, code, format, args);
565 g_warning (ERROR_OVERWRITTEN_WARNING, new->message);
571 * g_set_error_literal:
572 * @err: (allow-none): a return location for a #GError, or %NULL
573 * @domain: error domain
575 * @message: error message
577 * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
578 * must be %NULL. A new #GError is created and assigned to *@err.
579 * Unlike g_set_error(), @message is not a printf()-style format string.
580 * Use this function if @message contains text you don't have control over,
581 * that could include printf() escape sequences.
586 g_set_error_literal (GError **err,
589 const gchar *message)
595 *err = g_error_new_literal (domain, code, message);
597 g_warning (ERROR_OVERWRITTEN_WARNING, message);
602 * @dest: error return location
603 * @src: error to move into the return location
605 * If @dest is %NULL, free @src; otherwise, moves @src into *@dest.
606 * The error variable @dest points to must be %NULL.
609 g_propagate_error (GError **dest,
612 g_return_if_fail (src != NULL);
624 g_warning (ERROR_OVERWRITTEN_WARNING, src->message);
634 * @err: a #GError return location
636 * If @err is %NULL, does nothing. If @err is non-%NULL,
637 * calls g_error_free() on *@err and sets *@err to %NULL.
640 g_clear_error (GError **err)
651 g_error_add_prefix (gchar **string,
658 prefix = g_strdup_vprintf (format, ap);
660 *string = g_strconcat (prefix, oldstring, NULL);
667 * @err: (allow-none): a return location for a #GError, or %NULL
668 * @format: printf()-style format string
669 * @...: arguments to @format
671 * Formats a string according to @format and
672 * prefix it to an existing error message. If
673 * @err is %NULL (ie: no error variable) then do
676 * If *@err is %NULL (ie: an error variable is
677 * present but there is no error condition) then
678 * also do nothing. Whether or not it makes
679 * sense to take advantage of this feature is up
685 g_prefix_error (GError **err,
693 va_start (ap, format);
694 g_error_add_prefix (&(*err)->message, format, ap);
700 * g_propagate_prefixed_error:
701 * @dest: error return location
702 * @src: error to move into the return location
703 * @format: printf()-style format string
704 * @...: arguments to @format
706 * If @dest is %NULL, free @src; otherwise,
707 * moves @src into *@dest. *@dest must be %NULL.
708 * After the move, add a prefix as with
714 g_propagate_prefixed_error (GError **dest,
719 g_propagate_error (dest, src);
725 va_start (ap, format);
726 g_error_add_prefix (&(*dest)->message, format, ap);