Docs: Don't use the emphasis tag
[platform/upstream/glib.git] / glib / gerror.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 /*
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/.
23  */
24
25 /**
26  * SECTION:error_reporting
27  * @Title: Error Reporting
28  * @Short_description: a system for reporting errors
29  *
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.
37  *
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.)
45  *
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.
53  *
54  * Functions that can fail take a return location for a #GError as their
55  * last argument. For example:
56  * |[
57  * gboolean g_file_get_contents (const gchar  *filename,
58  *                               gchar       **contents,
59  *                               gsize        *length,
60  *                               GError      **error);
61  * ]|
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.
64  * For example:
65  * |[
66  * gchar *contents;
67  * GError *err = NULL;
68  * g_file_get_contents ("foo.txt", &amp;contents, NULL, &amp;err);
69  * g_assert ((contents == NULL &amp;&amp; err != NULL) || (contents != NULL &amp;&amp; err == NULL));
70  * if (err != NULL)
71  *   {
72  *     /&ast; Report error to user, and free error &ast;/
73  *     g_assert (contents == NULL);
74  *     fprintf (stderr, "Unable to read file: &percnt;s\n", err->message);
75  *     g_error_free (err);
76  *   }
77  * else
78  *   {
79  *     /&ast; Use file contents &ast;/
80  *     g_assert (contents != NULL);
81  *   }
82  * ]|
83  * Note that <literal>err != NULL</literal> in this example is a
84  * reliable indicator of whether g_file_get_contents() failed.
85  * Additionally, g_file_get_contents() returns a boolean which
86  * indicates whether it was successful.
87  *
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  * |[
92  * if (g_file_get_contents ("foo.txt", &amp;contents, NULL, NULL)) /&ast; ignore errors &ast;/
93  *   /&ast; no error occurred &ast;/ ;
94  * else
95  *   /&ast; error &ast;/ ;
96  * ]|
97  *
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).
111  *
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.
116  * Here's an example:
117  * |[
118  * gint
119  * foo_open_file (GError **error)
120  * {
121  *   gint fd;
122  *
123  *   fd = open ("file.txt", O_RDONLY);
124  *
125  *   if (fd &lt; 0)
126  *     {
127  *       g_set_error (error,
128  *                    FOO_ERROR,                 /&ast; error domain &ast;/
129  *                    FOO_ERROR_BLAH,            /&ast; error code &ast;/
130  *                    "Failed to open file: &percnt;s", /&ast; error message format string &ast;/
131  *                    g_strerror (errno));
132  *       return -1;
133  *     }
134  *   else
135  *     return fd;
136  * }
137  * ]|
138  *
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  * |[
144  * gboolean
145  * my_function_that_can_fail (GError **err)
146  * {
147  *   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
148  *
149  *   if (!sub_function_that_can_fail (err))
150  *     {
151  *       /&ast; assert that error was set by the sub-function &ast;/
152  *       g_assert (err == NULL || *err != NULL);
153  *       return FALSE;
154  *     }
155  *
156  *   /&ast; otherwise continue, no error occurred &ast;/
157  *   g_assert (err == NULL || *err == NULL);
158  * }
159  * ]|
160  *
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  * |[
166  * gboolean
167  * my_function_that_can_fail (GError **err)
168  * {
169  *   GError *tmp_error;
170  *
171  *   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
172  *
173  *   tmp_error = NULL;
174  *   sub_function_that_can_fail (&amp;tmp_error);
175  *
176  *   if (tmp_error != NULL)
177  *     {
178  *       /&ast; store tmp_error in err, if err != NULL,
179  *        &ast; otherwise call g_error_free() on tmp_error
180  *        &ast;/
181  *       g_propagate_error (err, tmp_error);
182  *       return FALSE;
183  *     }
184  *
185  *   /&ast; otherwise continue, no error occurred &ast;/
186  * }
187  * ]|
188  *
189  * Error pileups are always a bug. For example, this code is incorrect:
190  * |[
191  * gboolean
192  * my_function_that_can_fail (GError **err)
193  * {
194  *   GError *tmp_error;
195  *
196  *   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
197  *
198  *   tmp_error = NULL;
199  *   sub_function_that_can_fail (&amp;tmp_error);
200  *   other_function_that_can_fail (&amp;tmp_error);
201  *
202  *   if (tmp_error != NULL)
203  *     {
204  *       g_propagate_error (err, tmp_error);
205  *       return FALSE;
206  *     }
207  * }
208  * ]|
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.
212  *
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  * |[
218  * gboolean
219  * my_function_that_can_fail (GError **err)
220  * {
221  *   GError *tmp_error;
222  *
223  *   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
224  *
225  *   sub_function_that_can_fail (NULL); /&ast; ignore errors &ast;/
226  *
227  *   tmp_error = NULL;
228  *   other_function_that_can_fail (&amp;tmp_error);
229  *
230  *   if (tmp_error != NULL)
231  *     {
232  *       g_propagate_error (err, tmp_error);
233  *       return FALSE;
234  *     }
235  * }
236  * ]|
237  *
238  * Note that passing %NULL for the error location ignores errors; it's
239  * equivalent to
240  * <literal>try { sub_function_that_can_fail (); } catch (...) {}</literal>
241  * in C++. It does not mean to leave errors unhandled; it means to
242  * handle them by doing nothing.
243  *
244  * Error domains and codes are conventionally named as follows:
245  * <itemizedlist>
246  * <listitem><para>
247  *   The error domain is called
248  *   <literal>&lt;NAMESPACE&gt;_&lt;MODULE&gt;_ERROR</literal>,
249  *   for example %G_SPAWN_ERROR or %G_THREAD_ERROR:
250  *   |[
251  * #define G_SPAWN_ERROR g_spawn_error_quark ()
252  *
253  * GQuark
254  * g_spawn_error_quark (void)
255  * {
256  *   return g_quark_from_static_string ("g-spawn-error-quark");
257  * }
258  *   ]|
259  * </para></listitem>
260  * <listitem><para>
261  *   The quark function for the error domain is called
262  *   <literal>&lt;namespace&gt;_&lt;module&gt;_error_quark</literal>,
263  *   for example g_spawn_error_quark() or g_thread_error_quark().
264  * </para></listitem>
265  * <listitem><para>
266  *   The error codes are in an enumeration called
267  *   <literal>&lt;Namespace&gt;&lt;Module&gt;Error</literal>;
268  *   for example,#GThreadError or #GSpawnError.
269  * </para></listitem>
270  * <listitem><para>
271  *   Members of the error code enumeration are called
272  *   <literal>&lt;NAMESPACE&gt;_&lt;MODULE&gt;_ERROR_&lt;CODE&gt;</literal>,
273  *   for example %G_SPAWN_ERROR_FORK or %G_THREAD_ERROR_AGAIN.
274  * </para></listitem>
275  * <listitem><para>
276  *   If there's a "generic" or "unknown" error code for unrecoverable
277  *   errors it doesn't make sense to distinguish with specific codes,
278  *   it should be called <literal>&lt;NAMESPACE&gt;_&lt;MODULE&gt;_ERROR_FAILED</literal>,
279  *   for example %G_SPAWN_ERROR_FAILED.
280  * </para></listitem>
281  * </itemizedlist>
282  *
283  * Summary of rules for use of #GError:
284  * <itemizedlist>
285  * <listitem><para>
286  *   Do not report programming errors via #GError.
287  * </para></listitem>
288  * <listitem><para>
289  *   The last argument of a function that returns an error should
290  *   be a location where a #GError can be placed (i.e. "#GError** error").
291  *   If #GError is used with varargs, the #GError** should be the last
292  *   argument before the "...".
293  * </para></listitem>
294  * <listitem><para>
295  *   The caller may pass %NULL for the #GError** if they are not interested
296  *   in details of the exact error that occurred.
297  * </para></listitem>
298  * <listitem><para>
299  *   If %NULL is passed for the #GError** argument, then errors should
300  *   not be returned to the caller, but your function should still
301  *   abort and return if an error occurs. That is, control flow should
302  *   not be affected by whether the caller wants to get a #GError.
303  * </para></listitem>
304  * <listitem><para>
305  *   If a #GError is reported, then your function by definition had a
306  *   fatal failure and did not complete whatever it was supposed to do.
307  *   If the failure was not fatal, then you handled it and you should not
308  *   report it. If it was fatal, then you must report it and discontinue
309  *   whatever you were doing immediately.
310  * </para></listitem>
311  * <listitem><para>
312  *   If a #GError is reported, out parameters are not guaranteed to
313  *   be set to any defined value.
314  * </para></listitem>
315  * <listitem><para>
316  *   A #GError* must be initialized to %NULL before passing its address
317  *   to a function that can report errors.
318  * </para></listitem>
319  * <listitem><para>
320  *   "Piling up" errors is always a bug. That is, if you assign a
321  *   new #GError to a #GError* that is non-%NULL, thus overwriting
322  *   the previous error, it indicates that you should have aborted
323  *   the operation instead of continuing. If you were able to continue,
324  *   you should have cleared the previous error with g_clear_error().
325  *   g_set_error() will complain if you pile up errors.
326  * </para></listitem>
327  * <listitem><para>
328  *   By convention, if you return a boolean value indicating success
329  *   then %TRUE means success and %FALSE means failure. If %FALSE is
330  *   returned, the error must be set to a non-%NULL
331  *   value.
332  * </para></listitem>
333  * <listitem><para>
334  *   A %NULL return value is also frequently used to mean that an error
335  *   occurred. You should make clear in your documentation whether %NULL
336  *   is a valid return value in non-error cases; if %NULL is a valid value,
337  *   then users must check whether an error was returned to see if the
338  *   function succeeded.
339  * </para></listitem>
340  * <listitem><para>
341  *   When implementing a function that can report errors, you may want
342  *   to add a check at the top of your function that the error return
343  *   location is either %NULL or contains a %NULL error (e.g.
344  *   <literal>g_return_if_fail (error == NULL || *error == NULL);</literal>).
345  * </para></listitem>
346  * </itemizedlist>
347  */
348
349 #include "config.h"
350
351 #include "gerror.h"
352
353 #include "gslice.h"
354 #include "gstrfuncs.h"
355 #include "gtestutils.h"
356
357 /**
358  * g_error_new_valist:
359  * @domain: error domain
360  * @code: error code
361  * @format: printf()-style format for error message
362  * @args: #va_list of parameters for the message format
363  *
364  * Creates a new #GError with the given @domain and @code,
365  * and a message formatted with @format.
366  *
367  * Returns: a new #GError
368  *
369  * Since: 2.22
370  */
371 GError*
372 g_error_new_valist (GQuark       domain,
373                     gint         code,
374                     const gchar *format,
375                     va_list      args)
376 {
377   GError *error;
378
379   /* Historically, GError allowed this (although it was never meant to work),
380    * and it has significant use in the wild, which g_return_val_if_fail
381    * would break. It should maybe g_return_val_if_fail in GLib 4.
382    * (GNOME#660371, GNOME#560482)
383    */
384   g_warn_if_fail (domain != 0);
385   g_warn_if_fail (format != NULL);
386
387   error = g_slice_new (GError);
388
389   error->domain = domain;
390   error->code = code;
391   error->message = g_strdup_vprintf (format, args);
392
393   return error;
394 }
395
396 /**
397  * g_error_new:
398  * @domain: error domain
399  * @code: error code
400  * @format: printf()-style format for error message
401  * @...: parameters for message format
402  *
403  * Creates a new #GError with the given @domain and @code,
404  * and a message formatted with @format.
405  *
406  * Return value: a new #GError
407  */
408 GError*
409 g_error_new (GQuark       domain,
410              gint         code,
411              const gchar *format,
412              ...)
413 {
414   GError* error;
415   va_list args;
416
417   g_return_val_if_fail (format != NULL, NULL);
418   g_return_val_if_fail (domain != 0, NULL);
419
420   va_start (args, format);
421   error = g_error_new_valist (domain, code, format, args);
422   va_end (args);
423
424   return error;
425 }
426
427 /**
428  * g_error_new_literal:
429  * @domain: error domain
430  * @code: error code
431  * @message: error message
432  *
433  * Creates a new #GError; unlike g_error_new(), @message is
434  * not a printf()-style format string. Use this function if
435  * @message contains text you don't have control over,
436  * that could include printf() escape sequences.
437  *
438  * Return value: a new #GError
439  **/
440 GError*
441 g_error_new_literal (GQuark         domain,
442                      gint           code,
443                      const gchar   *message)
444 {
445   GError* err;
446
447   g_return_val_if_fail (message != NULL, NULL);
448   g_return_val_if_fail (domain != 0, NULL);
449
450   err = g_slice_new (GError);
451
452   err->domain = domain;
453   err->code = code;
454   err->message = g_strdup (message);
455
456   return err;
457 }
458
459 /**
460  * g_error_free:
461  * @error: a #GError
462  *
463  * Frees a #GError and associated resources.
464  */
465 void
466 g_error_free (GError *error)
467 {
468   g_return_if_fail (error != NULL);
469
470   g_free (error->message);
471
472   g_slice_free (GError, error);
473 }
474
475 /**
476  * g_error_copy:
477  * @error: a #GError
478  *
479  * Makes a copy of @error.
480  *
481  * Return value: a new #GError
482  */
483 GError*
484 g_error_copy (const GError *error)
485 {
486   GError *copy;
487  
488   g_return_val_if_fail (error != NULL, NULL);
489   /* See g_error_new_valist for why these don't return */
490   g_warn_if_fail (error->domain != 0);
491   g_warn_if_fail (error->message != NULL);
492
493   copy = g_slice_new (GError);
494
495   *copy = *error;
496
497   copy->message = g_strdup (error->message);
498
499   return copy;
500 }
501
502 /**
503  * g_error_matches:
504  * @error: (allow-none): a #GError or %NULL
505  * @domain: an error domain
506  * @code: an error code
507  *
508  * Returns %TRUE if @error matches @domain and @code, %FALSE
509  * otherwise. In particular, when @error is %NULL, %FALSE will
510  * be returned.
511  *
512  * Return value: whether @error has @domain and @code
513  */
514 gboolean
515 g_error_matches (const GError *error,
516                  GQuark        domain,
517                  gint          code)
518 {
519   return error &&
520     error->domain == domain &&
521     error->code == code;
522 }
523
524 #define ERROR_OVERWRITTEN_WARNING "GError set over the top of a previous GError or uninitialized memory.\n" \
525                "This indicates a bug in someone's code. You must ensure an error is NULL before it's set.\n" \
526                "The overwriting error message was: %s"
527
528 /**
529  * g_set_error:
530  * @err: (allow-none): a return location for a #GError, or %NULL
531  * @domain: error domain
532  * @code: error code
533  * @format: printf()-style format
534  * @...: args for @format
535  *
536  * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
537  * must be %NULL. A new #GError is created and assigned to *@err.
538  */
539 void
540 g_set_error (GError      **err,
541              GQuark        domain,
542              gint          code,
543              const gchar  *format,
544              ...)
545 {
546   GError *new;
547
548   va_list args;
549
550   if (err == NULL)
551     return;
552
553   va_start (args, format);
554   new = g_error_new_valist (domain, code, format, args);
555   va_end (args);
556
557   if (*err == NULL)
558     *err = new;
559   else
560     {
561       g_warning (ERROR_OVERWRITTEN_WARNING, new->message);
562       g_error_free (new);
563     }
564 }
565
566 /**
567  * g_set_error_literal:
568  * @err: (allow-none): a return location for a #GError, or %NULL
569  * @domain: error domain
570  * @code: error code
571  * @message: error message
572  *
573  * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
574  * must be %NULL. A new #GError is created and assigned to *@err.
575  * Unlike g_set_error(), @message is not a printf()-style format string.
576  * Use this function if @message contains text you don't have control over,
577  * that could include printf() escape sequences.
578  *
579  * Since: 2.18
580  */
581 void
582 g_set_error_literal (GError      **err,
583                      GQuark        domain,
584                      gint          code,
585                      const gchar  *message)
586 {
587   if (err == NULL)
588     return;
589
590   if (*err == NULL)
591     *err = g_error_new_literal (domain, code, message);
592   else
593     g_warning (ERROR_OVERWRITTEN_WARNING, message);
594 }
595
596 /**
597  * g_propagate_error:
598  * @dest: error return location
599  * @src: error to move into the return location
600  *
601  * If @dest is %NULL, free @src; otherwise, moves @src into *@dest.
602  * The error variable @dest points to must be %NULL.
603  */
604 void
605 g_propagate_error (GError **dest,
606                    GError  *src)
607 {
608   g_return_if_fail (src != NULL);
609  
610   if (dest == NULL)
611     {
612       if (src)
613         g_error_free (src);
614       return;
615     }
616   else
617     {
618       if (*dest != NULL)
619         {
620           g_warning (ERROR_OVERWRITTEN_WARNING, src->message);
621           g_error_free (src);
622         }
623       else
624         *dest = src;
625     }
626 }
627
628 /**
629  * g_clear_error:
630  * @err: a #GError return location
631  *
632  * If @err is %NULL, does nothing. If @err is non-%NULL,
633  * calls g_error_free() on *@err and sets *@err to %NULL.
634  */
635 void
636 g_clear_error (GError **err)
637 {
638   if (err && *err)
639     {
640       g_error_free (*err);
641       *err = NULL;
642     }
643 }
644
645 G_GNUC_PRINTF(2, 0)
646 static void
647 g_error_add_prefix (gchar       **string,
648                     const gchar  *format,
649                     va_list       ap)
650 {
651   gchar *oldstring;
652   gchar *prefix;
653
654   prefix = g_strdup_vprintf (format, ap);
655   oldstring = *string;
656   *string = g_strconcat (prefix, oldstring, NULL);
657   g_free (oldstring);
658   g_free (prefix);
659 }
660
661 /**
662  * g_prefix_error:
663  * @err: (allow-none): a return location for a #GError, or %NULL
664  * @format: printf()-style format string
665  * @...: arguments to @format
666  *
667  * Formats a string according to @format and prefix it to an existing
668  * error message. If @err is %NULL (ie: no error variable) then do
669  * nothing.
670  *
671  * If *@err is %NULL (ie: an error variable is present but there is no
672  * error condition) then also do nothing. Whether or not it makes sense
673  * to take advantage of this feature is up to you.
674  *
675  * Since: 2.16
676  */
677 void
678 g_prefix_error (GError      **err,
679                 const gchar  *format,
680                 ...)
681 {
682   if (err && *err)
683     {
684       va_list ap;
685
686       va_start (ap, format);
687       g_error_add_prefix (&(*err)->message, format, ap);
688       va_end (ap);
689     }
690 }
691
692 /**
693  * g_propagate_prefixed_error:
694  * @dest: error return location
695  * @src: error to move into the return location
696  * @format: printf()-style format string
697  * @...: arguments to @format
698  *
699  * If @dest is %NULL, free @src; otherwise, moves @src into *@dest.
700  * *@dest must be %NULL. After the move, add a prefix as with
701  * g_prefix_error().
702  *
703  * Since: 2.16
704  **/
705 void
706 g_propagate_prefixed_error (GError      **dest,
707                             GError       *src,
708                             const gchar  *format,
709                             ...)
710 {
711   g_propagate_error (dest, src);
712
713   if (dest && *dest)
714     {
715       va_list ap;
716
717       va_start (ap, format);
718       g_error_add_prefix (&(*dest)->message, format, ap);
719       va_end (ap);
720     }
721 }