2.25.0
[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 error codes are in an enumeration called 
261 <literal>&lt;Namespace&gt;&lt;Module&gt;Error</literal>; for example,
262 #GThreadError or #GSpawnError.
263 </para>
264 </listitem>
265 <listitem>
266 <para>
267 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. 
268 </para>
269 </listitem>
270 <listitem>
271 <para>
272 If there's a "generic" or "unknown" error code for unrecoverable errors it
273 doesn't make sense to distinguish with specific codes, it should be called 
274 <literal>&lt;NAMESPACE&gt;_&lt;MODULE&gt;_ERROR_FAILED</literal>, for 
275 example %G_SPAWN_ERROR_FAILED or %G_THREAD_ERROR_FAILED.
276 </para>
277 </listitem>
278 </itemizedlist>
279 </para>
280
281 <para>
282 Summary of rules for use of #GError:
283       <itemizedlist>
284         <listitem>
285           <para>
286            Do not report programming errors via #GError.
287           </para>
288         </listitem>
289
290       <listitem>
291         <para>
292           The last argument of a function that returns an error should be a
293           location where a #GError can be placed (i.e. "#GError** error").  If
294           #GError is used with varargs, the #GError** should be the last
295           argument before the "...".
296         </para>
297       </listitem>
298
299       <listitem>
300         <para>
301           The caller may pass %NULL for the #GError** if they are not interested
302           in details of the exact error that occurred.
303         </para>
304       </listitem>
305
306         <listitem>
307           <para>
308            If %NULL is passed for the #GError** argument, then errors should 
309            not be returned to the caller, but your function should still 
310            abort and return if an error occurs. That is, control flow should
311            not be affected by whether the caller wants to get a #GError.
312           </para>
313         </listitem>
314
315       <listitem>
316         <para>
317           If a #GError is reported, then your function by definition  
318           <emphasis>had a fatal failure and did not complete whatever it was supposed
319             to do</emphasis>. If the failure was not fatal, then you handled it
320           and you should not report it. If it was fatal, then you must report it 
321           and discontinue whatever you were doing immediately.
322         </para>
323       </listitem>
324
325         <listitem>
326           <para>
327           A #GError* must be initialized to %NULL before passing its address to
328           a function that can report errors.
329           </para>
330         </listitem>
331
332         <listitem>
333           <para>
334           "Piling up" errors is always a bug. That is, if you assign a new
335           #GError to a #GError* that is non-%NULL, thus overwriting the previous
336           error, it indicates that you should have aborted the operation instead
337           of continuing. If you were able to continue, you should have cleared
338           the previous error with g_clear_error(). g_set_error() will complain
339           if you pile up errors.
340           </para>
341         </listitem>
342
343
344         <listitem>
345           <para>
346           By convention, if you return a boolean value indicating success 
347           then %TRUE means success and %FALSE means failure. If %FALSE is returned,
348           the error <emphasis>must</emphasis> be set to a non-%NULL value. 
349         </para>
350         </listitem>
351
352
353         <listitem>
354           <para>
355           A %NULL return value is also frequently used to mean that an error
356           occurred.  You should make clear in your documentation whether %NULL is
357           a valid return value in non-error cases; if %NULL is a valid value,
358           then users must check whether an error was returned to see if the
359           function succeeded.
360           </para>
361         </listitem>
362
363         <listitem>
364           <para>
365           When implementing a function that can report errors, you may want to
366           add a check at the top of your function that the error return location
367           is either %NULL or contains a %NULL error
368           (e.g. <literal>g_return_if_fail (error == NULL || *error ==
369           NULL);</literal>).
370           </para>
371         </listitem>
372
373
374 </itemizedlist>
375 </para>
376
377 <!-- ##### SECTION See_Also ##### -->
378 <para>
379
380 </para>
381
382 <!-- ##### SECTION Stability_Level ##### -->
383
384
385 <!-- ##### SECTION Image ##### -->
386
387
388 <!-- ##### STRUCT GError ##### -->
389 <para>
390 The <structname>GError</structname> structure contains 
391 information about an error that has occurred.
392 </para>
393
394 @domain: error domain, e.g. #G_FILE_ERROR.
395 @code: error code, e.g. %G_FILE_ERROR_NOENT.
396 @message: human-readable informative error message.
397
398 <!-- ##### FUNCTION g_error_new ##### -->
399 <para>
400
401 </para>
402
403 @domain: 
404 @code: 
405 @format: 
406 @Varargs: 
407 @Returns: 
408
409
410 <!-- ##### FUNCTION g_error_new_literal ##### -->
411 <para>
412
413 </para>
414
415 @domain: 
416 @code: 
417 @message: 
418 @Returns: 
419
420
421 <!-- ##### FUNCTION g_error_new_valist ##### -->
422 <para>
423
424 </para>
425
426 @domain: 
427 @code: 
428 @format: 
429 @args: 
430 @Returns: 
431
432
433 <!-- ##### FUNCTION g_error_free ##### -->
434 <para>
435
436 </para>
437
438 @error: 
439
440
441 <!-- ##### FUNCTION g_error_copy ##### -->
442 <para>
443
444 </para>
445
446 @error: 
447 @Returns: 
448
449
450 <!-- ##### FUNCTION g_error_matches ##### -->
451 <para>
452
453 </para>
454
455 @error: 
456 @domain: 
457 @code: 
458 @Returns: 
459
460
461 <!-- ##### FUNCTION g_set_error ##### -->
462 <para>
463
464 </para>
465
466 @err: 
467 @domain: 
468 @code: 
469 @format: 
470 @Varargs: 
471
472
473 <!-- ##### FUNCTION g_set_error_literal ##### -->
474 <para>
475
476 </para>
477
478 @err: 
479 @domain: 
480 @code: 
481 @message: 
482
483
484 <!-- ##### FUNCTION g_propagate_error ##### -->
485 <para>
486
487 </para>
488
489 @dest: 
490 @src: 
491
492
493 <!-- ##### FUNCTION g_clear_error ##### -->
494 <para>
495
496 </para>
497
498 @err: <!--
499 Local variables:
500 mode: sgml
501 sgml-parent-document: ("../glib-docs.sgml" "book" "refsect2" "")
502 End:
503 -->
504
505
506 <!-- ##### FUNCTION g_prefix_error ##### -->
507 <para>
508
509 </para>
510
511 @err: 
512 @format: 
513 @Varargs: 
514
515
516 <!-- ##### FUNCTION g_propagate_prefixed_error ##### -->
517 <para>
518
519 </para>
520
521 @dest: 
522 @src: 
523 @format: 
524 @Varargs: 
525
526