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