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, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
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 <emphasis>data type</emphasis> (the #GError
36 * object) and a <emphasis>set of rules.</emphasis> If you use #GError
37 * incorrectly, then your code will not properly interoperate with other
38 * code that uses #GError, and users of your API will probably get confused.
40 * First and foremost: <emphasis>#GError should only be used to report
41 * recoverable runtime errors, never to report programming
42 * errors.</emphasis> If the programmer has screwed up, then you should
43 * use g_warning(), g_return_if_fail(), g_assert(), g_error(), or some
44 * similar facility. (Incidentally, remember that the g_error() function
45 * should <emphasis>only</emphasis> be used for programming errors, it
46 * should not be used to print any error 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. For example:
59 * gboolean g_file_get_contents (const gchar *filename,
64 * If you pass a non-%NULL value for the <literal>error</literal>
65 * argument, it should point to a location where an error can be placed.
70 * g_file_get_contents ("foo.txt", &contents, NULL, &err);
71 * g_assert ((contents == NULL && err != NULL) || (contents != NULL && err == NULL));
74 * /* Report error to user, and free error */
75 * g_assert (contents == NULL);
76 * fprintf (stderr, "Unable to read file: %s\n", err->message);
81 * /* Use file contents */
82 * g_assert (contents != NULL);
85 * Note that <literal>err != NULL</literal> in this example is a
86 * <emphasis>reliable</emphasis> indicator of whether
87 * g_file_get_contents() failed. Additionally, g_file_get_contents()
88 * returns a boolean which indicates whether it was successful.
90 * Because g_file_get_contents() returns %FALSE on failure, if you
91 * are only interested in whether it failed and don't need to display
92 * an error message, you can pass %NULL for the <literal>error</literal>
95 * if (g_file_get_contents ("foo.txt", &contents, NULL, NULL)) /* ignore errors */
96 * /* no error occurred */ ;
98 * /* error */ ;
101 * The #GError object contains three fields: <literal>domain</literal>
102 * indicates the module the error-reporting function is located in,
103 * <literal>code</literal> indicates the specific error that occurred,
104 * and <literal>message</literal> is a user-readable error message with
105 * as many details as possible. Several functions are provided to deal
106 * with an error received from a called function: g_error_matches()
107 * returns %TRUE if the error matches a given domain and code,
108 * g_propagate_error() copies an error into an error location (so the
109 * calling function will receive it), and g_clear_error() clears an
110 * error location by freeing the error and resetting the location to
111 * %NULL. To display an error to the user, simply display
112 * <literal>error->message</literal>, perhaps along with additional
113 * context known only to the calling function (the file being opened,
114 * or whatever -- though in the g_file_get_contents() case,
115 * <literal>error->message</literal> 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.
124 * foo_open_file (GError **error)
128 * fd = open ("file.txt", O_RDONLY);
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));
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:
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);
161 * /* otherwise continue, no error occurred */
162 * g_assert (err == NULL || *err == NULL);
166 * If the sub-function does not indicate errors other than by
167 * reporting a #GError, you need to create a temporary #GError
168 * since the passed-in one may be %NULL. g_propagate_error() is
169 * intended for use in this case.
172 * my_function_that_can_fail (GError **err)
176 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
179 * sub_function_that_can_fail (&tmp_error);
181 * if (tmp_error != NULL)
183 * /* store tmp_error in err, if err != NULL,
184 * * otherwise call g_error_free() on tmp_error
186 * g_propagate_error (err, tmp_error);
190 * /* otherwise continue, no error occurred */
194 * Error pileups are always a bug. For example, this code is incorrect:
197 * my_function_that_can_fail (GError **err)
201 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
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);
214 * <literal>tmp_error</literal> should be checked immediately after
215 * sub_function_that_can_fail(), and either cleared or propagated
216 * upward. The rule is: <emphasis>after each error, you must either
217 * handle the error, or return it to the calling function</emphasis>.
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():
224 * my_function_that_can_fail (GError **err)
228 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
230 * sub_function_that_can_fail (NULL); /* ignore errors */
233 * other_function_that_can_fail (&tmp_error);
235 * if (tmp_error != NULL)
237 * g_propagate_error (err, tmp_error);
243 * Note that passing %NULL for the error location
244 * <emphasis>ignores</emphasis> errors; it's equivalent to
245 * <literal>try { sub_function_that_can_fail (); } catch (...) {}</literal>
246 * in C++. It does <emphasis>not</emphasis> mean to leave errors
247 * unhandled; it means to handle them by doing nothing.
249 * Error domains and codes are conventionally named as follows:
252 * The error domain is called
253 * <literal><NAMESPACE>_<MODULE>_ERROR</literal>,
254 * for example %G_SPAWN_ERROR or %G_THREAD_ERROR:
256 * #define G_SPAWN_ERROR g_spawn_error_quark ()
259 * g_spawn_error_quark (void)
261 * return g_quark_from_static_string ("g-spawn-error-quark");
266 * The quark function for the error domain is called
267 * <literal><namespace>_<module>_error_quark</literal>,
268 * for example g_spawn_error_quark() or %g_thread_error_quark().
271 * The error codes are in an enumeration called
272 * <literal><Namespace><Module>Error</literal>;
273 * for example,#GThreadError or #GSpawnError.
276 * Members of the error code enumeration are called
277 * <literal><NAMESPACE>_<MODULE>_ERROR_<CODE></literal>,
278 * for example %G_SPAWN_ERROR_FORK or %G_THREAD_ERROR_AGAIN.
281 * If there's a "generic" or "unknown" error code for unrecoverable
282 * errors it doesn't make sense to distinguish with specific codes,
283 * it should be called <literal><NAMESPACE>_<MODULE>_ERROR_FAILED</literal>,
284 * for example %G_SPAWN_ERROR_FAILED or %G_THREAD_ERROR_FAILED.
288 * Summary of rules for use of #GError:
291 * Do not report programming errors via #GError.
294 * The last argument of a function that returns an error should
295 * be a location where a #GError can be placed (i.e. "#GError** error").
296 * If #GError is used with varargs, the #GError** should be the last
297 * argument before the "...".
300 * The caller may pass %NULL for the #GError** if they are not interested
301 * in details of the exact error that occurred.
304 * If %NULL is passed for the #GError** argument, then errors should
305 * not be returned to the caller, but your function should still
306 * abort and return if an error occurs. That is, control flow should
307 * not be affected by whether the caller wants to get a #GError.
310 * If a #GError is reported, then your function by definition
311 * <emphasis>had a fatal failure and did not complete whatever
312 * it was supposed to do</emphasis>. If the failure was not fatal,
313 * then you handled it and you should not report it. If it was fatal,
314 * then you must report it and discontinue whatever you were doing
318 * A #GError* must be initialized to %NULL before passing its address
319 * to a function that can report errors.
322 * "Piling up" errors is always a bug. That is, if you assign a
323 * new #GError to a #GError* that is non-%NULL, thus overwriting
324 * the previous error, it indicates that you should have aborted
325 * the operation instead of continuing. If you were able to continue,
326 * you should have cleared the previous error with g_clear_error().
327 * g_set_error() will complain if you pile up errors.
330 * By convention, if you return a boolean value indicating success
331 * then %TRUE means success and %FALSE means failure. If %FALSE is
332 * returned, the error <emphasis>must</emphasis> be set to a non-%NULL
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.
343 * When implementing a function that can report errors, you may want
344 * to add a check at the top of your function that the error return
345 * location is either %NULL or contains a %NULL error (e.g.
346 * <literal>g_return_if_fail (error == NULL || *error == NULL);</literal>).
355 #include "gstrfuncs.h"
356 #include "gtestutils.h"
359 * g_error_new_valist:
360 * @domain: error domain
362 * @format: printf()-style format for error message
363 * @args: #va_list of parameters for the message format
365 * Creates a new #GError with the given @domain and @code,
366 * and a message formatted with @format.
368 * Returns: a new #GError
373 g_error_new_valist (GQuark domain,
380 error = g_slice_new (GError);
382 error->domain = domain;
384 error->message = g_strdup_vprintf (format, args);
391 * @domain: error domain
393 * @format: printf()-style format for error message
394 * @...: parameters for message format
396 * Creates a new #GError with the given @domain and @code,
397 * and a message formatted with @format.
399 * Return value: a new #GError
402 g_error_new (GQuark domain,
410 g_return_val_if_fail (format != NULL, NULL);
411 g_return_val_if_fail (domain != 0, NULL);
413 va_start (args, format);
414 error = g_error_new_valist (domain, code, format, args);
421 * g_error_new_literal:
422 * @domain: error domain
424 * @message: error message
426 * Creates a new #GError; unlike g_error_new(), @message is
427 * not a printf()-style format string. Use this function if
428 * @message contains text you don't have control over,
429 * that could include printf() escape sequences.
431 * Return value: a new #GError
434 g_error_new_literal (GQuark domain,
436 const gchar *message)
440 g_return_val_if_fail (message != NULL, NULL);
441 g_return_val_if_fail (domain != 0, NULL);
443 err = g_slice_new (GError);
445 err->domain = domain;
447 err->message = g_strdup (message);
456 * Frees a #GError and associated resources.
459 g_error_free (GError *error)
461 g_return_if_fail (error != NULL);
463 g_free (error->message);
465 g_slice_free (GError, error);
472 * Makes a copy of @error.
474 * Return value: a new #GError
477 g_error_copy (const GError *error)
481 g_return_val_if_fail (error != NULL, NULL);
483 copy = g_slice_new (GError);
487 copy->message = g_strdup (error->message);
494 * @error: a #GError or %NULL
495 * @domain: an error domain
496 * @code: an error code
498 * Returns %TRUE if @error matches @domain and @code, %FALSE
499 * otherwise. In particular, when @error is %NULL, %FALSE will
502 * Return value: whether @error has @domain and @code
505 g_error_matches (const GError *error,
510 error->domain == domain &&
514 #define ERROR_OVERWRITTEN_WARNING "GError set over the top of a previous GError or uninitialized memory.\n" \
515 "This indicates a bug in someone's code. You must ensure an error is NULL before it's set.\n" \
516 "The overwriting error message was: %s"
520 * @err: a return location for a #GError, or %NULL
521 * @domain: error domain
523 * @format: printf()-style format
524 * @...: args for @format
526 * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
527 * must be %NULL. A new #GError is created and assigned to *@err.
530 g_set_error (GError **err,
543 va_start (args, format);
544 new = g_error_new_valist (domain, code, format, args);
550 g_warning (ERROR_OVERWRITTEN_WARNING, new->message);
554 * g_set_error_literal:
555 * @err: a return location for a #GError, or %NULL
556 * @domain: error domain
558 * @message: error message
560 * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
561 * must be %NULL. A new #GError is created and assigned to *@err.
562 * Unlike g_set_error(), @message is not a printf()-style format string.
563 * Use this function if @message contains text you don't have control over,
564 * that could include printf() escape sequences.
569 g_set_error_literal (GError **err,
572 const gchar *message)
579 new = g_error_new_literal (domain, code, message);
583 g_warning (ERROR_OVERWRITTEN_WARNING, new->message);
588 * @dest: error return location
589 * @src: error to move into the return location
591 * If @dest is %NULL, free @src; otherwise, moves @src into *@dest.
592 * The error variable @dest points to must be %NULL.
595 g_propagate_error (GError **dest,
598 g_return_if_fail (src != NULL);
609 g_warning (ERROR_OVERWRITTEN_WARNING, src->message);
617 * @err: a #GError return location
619 * If @err is %NULL, does nothing. If @err is non-%NULL,
620 * calls g_error_free() on *@err and sets *@err to %NULL.
623 g_clear_error (GError **err)
633 g_error_add_prefix (gchar **string,
640 prefix = g_strdup_vprintf (format, ap);
642 *string = g_strconcat (prefix, oldstring, NULL);
649 * @err: a return location for a #GError, or %NULL
650 * @format: printf()-style format string
651 * @...: arguments to @format
653 * Formats a string according to @format and
654 * prefix it to an existing error message. If
655 * @err is %NULL (ie: no error variable) then do
658 * If *@err is %NULL (ie: an error variable is
659 * present but there is no error condition) then
660 * also do nothing. Whether or not it makes
661 * sense to take advantage of this feature is up
667 g_prefix_error (GError **err,
675 va_start (ap, format);
676 g_error_add_prefix (&(*err)->message, format, ap);
682 * g_propagate_prefixed_error:
683 * @dest: error return location
684 * @src: error to move into the return location
685 * @format: printf()-style format string
686 * @...: arguments to @format
688 * If @dest is %NULL, free @src; otherwise,
689 * moves @src into *@dest. *@dest must be %NULL.
690 * After the move, add a prefix as with
696 g_propagate_prefixed_error (GError **dest,
701 g_propagate_error (dest, src);
707 va_start (ap, format);
708 g_error_add_prefix (&(*dest)->message, format, ap);