895fff3c4798aa4e81219972289bcd7658758c78
[platform/upstream/glib.git] / docs / reference / glib / tmpl / error_reporting.sgml
1 <!-- ##### SECTION Title ##### -->
2 Error Reporting
3
4 <!-- ##### SECTION Short_Description ##### -->
5 a system for reporting errors
6
7 <!-- ##### SECTION Long_Description ##### -->
8
9 <para>
10 GLib provides a standard method of reporting errors from a called function to
11 the calling code. (This is the same problem solved by exceptions in other
12 languages.) It's important to understand that this method is both a
13 <emphasis>data type</emphasis> (the #GError object) and a <emphasis>set of
14 rules.</emphasis> If you use #GError incorrectly, then your code will not
15 properly interoperate with other code that uses #GError, and users of your API
16 will probably get confused.
17 </para>
18
19 <para>
20 First and foremost: <emphasis>#GError should only be used to report
21 recoverable runtime errors, never to report programming errors.</emphasis> If
22 the programmer has screwed up, then you should use g_warning(),
23 g_return_if_fail(), g_assert(), g_error(), or some similar facility.
24 (Incidentally, remember that the g_error() function should
25 <emphasis>only</emphasis> be used for programming errors, it should not be used
26 to print any error reportable via #GError.)
27 </para>
28
29 <para>
30 Examples of recoverable runtime errors are "file not found" or "failed to parse
31 input." Examples of programming errors are "NULL passed to strcmp()" or
32 "attempted to free the same pointer twice." These two kinds of errors are
33 fundamentally different: runtime errors should be handled or reported to the
34 user, programming errors should be eliminated by fixing the bug in the program.
35 This is why most functions in GLib and GTK+ do not use the #GError facility.
36 </para>
37
38 <para>
39 Functions that can fail take a return location for a #GError as their last argument. 
40 For example:
41 <informalexample><programlisting>
42 gboolean g_file_get_contents (const gchar *filename, 
43                               gchar      **contents,
44                               gsize       *length,
45                               GError     **error);
46 </programlisting></informalexample>
47 If you pass a non-%NULL value for the <literal>error</literal> argument, it should 
48 point to a location where an error can be placed. For example:
49 <informalexample><programlisting>
50 gchar *contents;
51 GError *err = NULL;
52 g_file_get_contents ("foo.txt", &amp;contents, NULL, &amp;err);
53 g_assert ((contents == NULL &amp;&amp; err != NULL) || (contents != NULL &amp;&amp; err == NULL));
54 if (err != NULL)
55   {
56     /* Report error to user, and free error */
57     g_assert (contents == NULL);
58     fprintf (stderr, "Unable to read file: &percnt;s\n", err->message);
59     g_error_free (err);
60   } 
61 else
62   {
63     /* Use file contents */
64     g_assert (contents != NULL);
65   }
66 </programlisting></informalexample>
67 Note that <literal>err != NULL</literal> in this example is a
68 <emphasis>reliable</emphasis> indicator of whether
69 g_file_get_contents() failed. Additionally, g_file_get_contents() returns
70 a boolean which indicates whether it was successful.
71 </para>
72
73 <para>
74 Because g_file_get_contents() returns %FALSE on failure, if you are only
75 interested in whether it failed and don't need to display an error message, you
76 can pass %NULL for the <literal>error</literal> argument:
77 <informalexample><programlisting>
78 if (g_file_get_contents ("foo.txt", &amp;contents, NULL, NULL)) /* ignore errors */
79   /* no error occurred */ ;
80 else
81   /* error */ ;
82 </programlisting></informalexample>
83 </para>
84
85 <para>
86 The #GError object contains three fields: <literal>domain</literal> indicates
87 the module the error-reporting function is located in, <literal>code</literal>
88 indicates the specific error that occurred, and <literal>message</literal> is a
89 user-readable error message with as many details as possible. Several functions
90 are provided to deal with an error received from a called function:
91 g_error_matches() returns %TRUE if the error matches a given domain and code,
92 g_propagate_error() copies an error into an error location (so the calling
93 function will receive it), and g_clear_error() clears an error location by
94 freeing the error and resetting the location to %NULL. To display an error to the
95 user, simply display <literal>error-&gt;message</literal>, perhaps along with
96 additional context known only to the calling function (the file being opened, or
97 whatever -- though in the g_file_get_contents() case,
98 <literal>error-&gt;message</literal> already contains a filename).
99 </para>
100
101 <para>
102 When implementing a function that can report errors, the basic tool is
103 g_set_error(). Typically, if a fatal error occurs you want to g_set_error(),
104 then return immediately. g_set_error() does nothing if the error location passed
105 to it is %NULL. Here's an example:
106 <informalexample><programlisting>
107 gint
108 foo_open_file (GError **error)
109 {
110   gint fd;
111
112   fd = open ("file.txt", O_RDONLY);
113
114   if (fd &lt; 0)
115     {
116       g_set_error (error,
117                    FOO_ERROR,                 /* error domain */
118                    FOO_ERROR_BLAH,            /* error code */
119                    "Failed to open file: &percnt;s", /* error message format string */
120                    g_strerror (errno));
121       return -1;
122     }
123   else
124     return fd;
125 }
126 </programlisting></informalexample>
127 </para>
128
129 <para>
130 Things are somewhat more complicated if you yourself call another function that
131 can report a #GError. If the sub-function indicates fatal errors in some way
132 other than reporting a #GError, such as by returning %TRUE on success, you can
133 simply do the following:
134 <informalexample><programlisting>
135 gboolean
136 my_function_that_can_fail (GError **err)
137 {
138   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
139
140   if (!sub_function_that_can_fail (err))
141     {
142        /* assert that error was set by the sub-function */
143        g_assert (err == NULL || *err != NULL);  
144        return FALSE;
145     }
146
147   /* otherwise continue, no error occurred */
148   g_assert (err == NULL || *err == NULL);
149 }
150 </programlisting></informalexample>
151 </para>
152
153 <para>
154 If the sub-function does not indicate errors other than by reporting a #GError, 
155 you need to create a temporary #GError since the passed-in one may be %NULL.
156 g_propagate_error() is intended for use in this case.
157 <informalexample><programlisting>
158 gboolean
159 my_function_that_can_fail (GError **err)
160 {
161   GError *tmp_error;
162
163   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
164
165   tmp_error = NULL;
166   sub_function_that_can_fail (&amp;tmp_error);
167
168   if (tmp_error != NULL)
169     {
170        /* store tmp_error in err, if err != NULL,
171         * otherwise call g_error_free(<!-- -->) on tmp_error 
172         */
173        g_propagate_error (err, tmp_error);
174        return FALSE;
175     }
176
177   /* otherwise continue, no error occurred */
178 }
179 </programlisting></informalexample>
180 </para>
181
182 <para>
183 Error pileups are always a bug. For example, this code is incorrect:
184 <informalexample><programlisting>
185 gboolean
186 my_function_that_can_fail (GError **err)
187 {
188   GError *tmp_error;
189
190   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
191
192   tmp_error = NULL;
193   sub_function_that_can_fail (&amp;tmp_error);
194   other_function_that_can_fail (&amp;tmp_error);
195
196   if (tmp_error != NULL)
197     {
198        g_propagate_error (err, tmp_error);
199        return FALSE;
200     }
201 }
202 </programlisting></informalexample>
203 <literal>tmp_error</literal> should be checked immediately after
204 <function>sub_function_that_can_fail()</function>, and either cleared or propagated upward.  The rule
205 is: <emphasis>after each error, you must either handle the error, or return it to the
206 calling function</emphasis>.  Note that passing %NULL for the error location is the
207 equivalent of handling an error by always doing nothing about it. So the
208 following code is fine, assuming errors in <function>sub_function_that_can_fail()</function> are not
209 fatal to <function>my_function_that_can_fail()</function>:
210 <informalexample><programlisting>
211 gboolean
212 my_function_that_can_fail (GError **err)
213 {
214   GError *tmp_error;
215
216   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
217
218   sub_function_that_can_fail (NULL); /* ignore errors */
219
220   tmp_error = NULL;
221   other_function_that_can_fail (&amp;tmp_error);
222
223   if (tmp_error != NULL)
224     {
225        g_propagate_error (err, tmp_error);
226        return FALSE;
227     }
228 }
229 </programlisting></informalexample>
230 </para>
231
232 <para>
233 Note that passing %NULL for the error location <emphasis>ignores</emphasis>
234 errors; it's equivalent to <literal>try { sub_function_that_can_fail (); } catch
235 (...) {}</literal> in C++. It does <emphasis>not</emphasis> mean to leave errors
236 unhandled; it means to handle them by doing nothing.
237 </para>
238
239 <para>
240 Error domains and codes are conventionally named as follows:
241 <itemizedlist>
242 <listitem>
243 <para>
244 The error domain is called 
245 <literal>&lt;NAMESPACE&gt;_&lt;MODULE&gt;_ERROR</literal>, for example
246 %G_SPAWN_ERROR or %G_THREAD_ERROR:
247 <informalexample><programlisting>
248 #define G_SPAWN_ERROR g_spawn_error_quark (<!-- -->)
249
250 GQuark
251 g_spawn_error_quark (void)
252 {
253   return g_quark_from_static_string ("g-spawn-error-quark");
254 }
255 </programlisting></informalexample>
256 </para>
257 </listitem>
258 <listitem>
259 <para>
260 The quark function for the error domain is called <literal>&lt;namespace&gt;_&lt;module&gt;_error_quark</literal>, for example g_spawn_error_quark() or %g_thread_error_quark().
261 </para>
262 </listitem>
263 <listitem>
264 <para>
265 The error codes are in an enumeration called 
266 <literal>&lt;Namespace&gt;&lt;Module&gt;Error</literal>; for example,
267 #GThreadError or #GSpawnError.
268 </para>
269 </listitem>
270 <listitem>
271 <para>
272 Members of the error code enumeration are called <literal>&lt;NAMESPACE&gt;_&lt;MODULE&gt;_ERROR_&lt;CODE&gt;</literal>, for example %G_SPAWN_ERROR_FORK or %G_THREAD_ERROR_AGAIN. 
273 </para>
274 </listitem>
275 <listitem>
276 <para>
277 If there's a "generic" or "unknown" error code for unrecoverable errors it
278 doesn't make sense to distinguish with specific codes, it should be called 
279 <literal>&lt;NAMESPACE&gt;_&lt;MODULE&gt;_ERROR_FAILED</literal>, for 
280 example %G_SPAWN_ERROR_FAILED or %G_THREAD_ERROR_FAILED.
281 </para>
282 </listitem>
283 </itemizedlist>
284 </para>
285
286 <para>
287 Summary of rules for use of #GError:
288       <itemizedlist>
289         <listitem>
290           <para>
291            Do not report programming errors via #GError.
292           </para>
293         </listitem>
294
295       <listitem>
296         <para>
297           The last argument of a function that returns an error should be a
298           location where a #GError can be placed (i.e. "#GError** error").  If
299           #GError is used with varargs, the #GError** should be the last
300           argument before the "...".
301         </para>
302       </listitem>
303
304       <listitem>
305         <para>
306           The caller may pass %NULL for the #GError** if they are not interested
307           in details of the exact error that occurred.
308         </para>
309       </listitem>
310
311         <listitem>
312           <para>
313            If %NULL is passed for the #GError** argument, then errors should 
314            not be returned to the caller, but your function should still 
315            abort and return if an error occurs. That is, control flow should
316            not be affected by whether the caller wants to get a #GError.
317           </para>
318         </listitem>
319
320       <listitem>
321         <para>
322           If a #GError is reported, then your function by definition  
323           <emphasis>had a fatal failure and did not complete whatever it was supposed
324             to do</emphasis>. If the failure was not fatal, then you handled it
325           and you should not report it. If it was fatal, then you must report it 
326           and discontinue whatever you were doing immediately.
327         </para>
328       </listitem>
329
330         <listitem>
331           <para>
332           A #GError* must be initialized to %NULL before passing its address to
333           a function that can report errors.
334           </para>
335         </listitem>
336
337         <listitem>
338           <para>
339           "Piling up" errors is always a bug. That is, if you assign a new
340           #GError to a #GError* that is non-%NULL, thus overwriting the previous
341           error, it indicates that you should have aborted the operation instead
342           of continuing. If you were able to continue, you should have cleared
343           the previous error with g_clear_error(). g_set_error() will complain
344           if you pile up errors.
345           </para>
346         </listitem>
347
348
349         <listitem>
350           <para>
351           By convention, if you return a boolean value indicating success 
352           then %TRUE means success and %FALSE means failure. If %FALSE is returned,
353           the error <emphasis>must</emphasis> be set to a non-%NULL value. 
354         </para>
355         </listitem>
356
357
358         <listitem>
359           <para>
360           A %NULL return value is also frequently used to mean that an error
361           occurred.  You should make clear in your documentation whether %NULL is
362           a valid return value in non-error cases; if %NULL is a valid value,
363           then users must check whether an error was returned to see if the
364           function succeeded.
365           </para>
366         </listitem>
367
368         <listitem>
369           <para>
370           When implementing a function that can report errors, you may want to
371           add a check at the top of your function that the error return location
372           is either %NULL or contains a %NULL error
373           (e.g. <literal>g_return_if_fail (error == NULL || *error ==
374           NULL);</literal>).
375           </para>
376         </listitem>
377
378
379 </itemizedlist>
380 </para>
381
382 <!-- ##### SECTION See_Also ##### -->
383 <para>
384
385 </para>
386
387 <!-- ##### SECTION Stability_Level ##### -->
388
389
390 <!-- ##### SECTION Image ##### -->
391
392
393 <!-- ##### STRUCT GError ##### -->
394 <para>
395 The <structname>GError</structname> structure contains 
396 information about an error that has occurred.
397 </para>
398
399 @domain: error domain, e.g. #G_FILE_ERROR.
400 @code: error code, e.g. %G_FILE_ERROR_NOENT.
401 @message: human-readable informative error message.
402
403 <!-- ##### FUNCTION g_error_new ##### -->
404 <para>
405
406 </para>
407
408 @domain: 
409 @code: 
410 @format: 
411 @Varargs: 
412 @Returns: 
413
414
415 <!-- ##### FUNCTION g_error_new_literal ##### -->
416 <para>
417
418 </para>
419
420 @domain: 
421 @code: 
422 @message: 
423 @Returns: 
424
425
426 <!-- ##### FUNCTION g_error_new_valist ##### -->
427 <para>
428
429 </para>
430
431 @domain: 
432 @code: 
433 @format: 
434 @args: 
435 @Returns: 
436
437
438 <!-- ##### FUNCTION g_error_free ##### -->
439 <para>
440
441 </para>
442
443 @error: 
444
445
446 <!-- ##### FUNCTION g_error_copy ##### -->
447 <para>
448
449 </para>
450
451 @error: 
452 @Returns: 
453
454
455 <!-- ##### FUNCTION g_error_matches ##### -->
456 <para>
457
458 </para>
459
460 @error: 
461 @domain: 
462 @code: 
463 @Returns: 
464
465
466 <!-- ##### FUNCTION g_set_error ##### -->
467 <para>
468
469 </para>
470
471 @err: 
472 @domain: 
473 @code: 
474 @format: 
475 @Varargs: 
476
477
478 <!-- ##### FUNCTION g_set_error_literal ##### -->
479 <para>
480
481 </para>
482
483 @err: 
484 @domain: 
485 @code: 
486 @message: 
487
488
489 <!-- ##### FUNCTION g_propagate_error ##### -->
490 <para>
491
492 </para>
493
494 @dest: 
495 @src: 
496
497
498 <!-- ##### FUNCTION g_clear_error ##### -->
499 <para>
500
501 </para>
502
503 @err: <!--
504 Local variables:
505 mode: sgml
506 sgml-parent-document: ("../glib-docs.sgml" "book" "refsect2" "")
507 End:
508 -->
509
510
511 <!-- ##### FUNCTION g_prefix_error ##### -->
512 <para>
513
514 </para>
515
516 @err: 
517 @format: 
518 @Varargs: 
519
520
521 <!-- ##### FUNCTION g_propagate_prefixed_error ##### -->
522 <para>
523
524 </para>
525
526 @dest: 
527 @src: 
528 @format: 
529 @Varargs: 
530
531