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