c78bc8791c595c6d0759e593c8a46cdb8dbf55bb
[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 gchar* g_file_get_contents (const gchar *filename, GError **error);
43 </programlisting></informalexample>
44 If you pass a non-%NULL value for the <literal>error</literal> argument, it should 
45 point to a location where an error can be placed. For example:
46 <informalexample><programlisting>
47 gchar *contents;
48 GError *err = NULL;
49 contents = g_file_get_contents ("foo.txt", &amp;err);
50 g_assert ((contents == NULL &amp;&amp; err != NULL) || (contents != NULL &amp;&amp; err == NULL));
51 if (err != NULL)
52   {
53     /* Report error to user, and free error */
54     g_assert (contents == NULL);
55     fprintf (stderr, "Unable to read file: &percnt;s\n", err->message);
56     g_error_free (err);
57   } 
58 else
59   {
60     /* Use file contents */
61     g_assert (contents != NULL);
62   }
63 </programlisting></informalexample>
64 Note that <literal>err != NULL</literal> in this example is a
65 <emphasis>reliable</emphasis> indicator of whether
66 g_file_get_contents() failed. Also, g_file_get_contents() uses the
67 convention that a %NULL return value means an error occurred (but not
68 all functions use this convention).
69 </para>
70
71 <para>
72 Because g_file_get_contents() returns %NULL on failure, if you are only
73 interested in whether it failed and don't need to display an error message, you
74 can pass %NULL for the <literal>error</literal> argument:
75 <informalexample><programlisting>
76 contents = g_file_get_contents ("foo.txt", NULL); /* ignore errors */
77 if (contents != NULL)
78   /* no error occurred */ ;
79 else
80   /* error */ ;
81 </programlisting></informalexample>
82 </para>
83
84 <para>
85 The #GError object contains three fields: <literal>domain</literal> indicates
86 the module the error-reporting function is located in, <literal>code</literal>
87 indicates the specific error that occurred, and <literal>message</literal> is a
88 user-readable error message with as many details as possible. Several functions
89 are provided to deal with an error received from a called function:
90 g_error_matches() returns %TRUE if the error matches a given domain and code,
91 g_propagate_error() copies an error into an error location (so the calling
92 function will receive it), and g_clear_error() clears an error location by
93 freeing the error and resetting the location to %NULL. To display an error to the
94 user, simply display <literal>error-&gt;message</literal>, perhaps along with
95 additional context known only to the calling function (the file being opened, or
96 whatever -- though in the g_file_get_contents() case,
97 <literal>error-&gt;message</literal> already contains a filename).
98 </para>
99
100 <para>
101 When implementing a function that can report errors, the basic tool is
102 g_set_error(). Typically, if a fatal error occurs you want to g_set_error(),
103 then return immediately. g_set_error() does nothing if the error location passed
104 to it is %NULL. Here's an example:
105 <informalexample><programlisting>
106 gint
107 foo_open_file (GError **error)
108 {
109   gint fd;
110
111   fd = open ("file.txt", O_RDONLY);
112
113   if (fd &lt; 0)
114     {
115       g_set_error (error,
116                    FOO_ERROR,                 /* error domain */
117                    FOO_ERROR_BLAH,            /* error code */
118                    "Failed to open file: &percnt;s", /* error message format string */
119                    g_strerror (errno));
120       return -1;
121     }
122   else
123     return fd;
124 }
125 </programlisting></informalexample>
126 </para>
127
128 <para>
129 Things are somewhat more complicated if you yourself call another function that
130 can report a #GError. If the sub-function indicates fatal errors in some way
131 other than reporting a #GError, such as by returning %TRUE on success, you can
132 simply do the following:
133 <informalexample><programlisting>
134 gboolean
135 my_function_that_can_fail (GError **err)
136 {
137   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
138
139   if (!sub_function_that_can_fail (err))
140     {
141        /* assert that error was set by the sub-function */
142        g_assert (err == NULL || *err != NULL);  
143        return FALSE;
144     }
145
146   /* otherwise continue, no error occurred */
147   g_assert (err == NULL || *err == NULL);
148 }
149 </programlisting></informalexample>
150 </para>
151
152 <para>
153 If the sub-function does not indicate errors other than by reporting a #GError, 
154 you need to create a temporary #GError since the passed-in one may be %NULL.
155 g_propagate_error() is intended for use in this case.
156 <informalexample><programlisting>
157 gboolean
158 my_function_that_can_fail (GError **err)
159 {
160   GError *tmp_error;
161
162   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
163
164   tmp_error = NULL;
165   sub_function_that_can_fail (&amp;tmp_error);
166
167   if (tmp_error != NULL)
168     {
169        /* store tmp_error in err, if err != NULL,
170         * otherwise call g_error_free(<!-- -->) on tmp_error 
171         */
172        g_propagate_error (err, tmp_error);
173        return FALSE;
174     }
175
176   /* otherwise continue, no error occurred */
177 }
178 </programlisting></informalexample>
179 </para>
180
181 <para>
182 Error pileups are always a bug. For example, this code is incorrect:
183 <informalexample><programlisting>
184 gboolean
185 my_function_that_can_fail (GError **err)
186 {
187   GError *tmp_error;
188
189   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
190
191   tmp_error = NULL;
192   sub_function_that_can_fail (&amp;tmp_error);
193   other_function_that_can_fail (&amp;tmp_error);
194
195   if (tmp_error != NULL)
196     {
197        g_propagate_error (err, tmp_error);
198        return FALSE;
199     }
200 }
201 </programlisting></informalexample>
202 <literal>tmp_error</literal> should be checked immediately after
203 <function>sub_function_that_can_fail()</function>, and either cleared or propagated upward.  The rule
204 is: <emphasis>after each error, you must either handle the error, or return it to the
205 calling function</emphasis>.  Note that passing %NULL for the error location is the
206 equivalent of handling an error by always doing nothing about it. So the
207 following code is fine, assuming errors in <function>sub_function_that_can_fail()</function> are not
208 fatal to <function>my_function_that_can_fail()</function>:
209 <informalexample><programlisting>
210 gboolean
211 my_function_that_can_fail (GError **err)
212 {
213   GError *tmp_error;
214
215   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
216
217   sub_function_that_can_fail (NULL); /* ignore errors */
218
219   tmp_error = NULL;
220   other_function_that_can_fail (&amp;tmp_error);
221
222   if (tmp_error != NULL)
223     {
224        g_propagate_error (err, tmp_error);
225        return FALSE;
226     }
227 }
228 </programlisting></informalexample>
229 </para>
230
231 <para>
232 Note that passing %NULL for the error location <emphasis>ignores</emphasis>
233 errors; it's equivalent to <literal>try { sub_function_that_can_fail (); } catch
234 (...) {}</literal> in C++. It does <emphasis>not</emphasis> mean to leave errors
235 unhandled; it means to handle them by doing nothing.
236 </para>
237
238 <para>
239 Error domains and codes are conventionally named as follows:
240 <itemizedlist>
241 <listitem>
242 <para>
243 The error domain is called
244 <literal>&lt;NAMESPACE&gt;_&lt;MODULE&gt;_ERROR</literal>, for example
245 %G_EXEC_ERROR or %G_THREAD_ERROR.
246 </para>
247 </listitem>
248 <listitem>
249 <para>
250 The error codes are in an enumeration called 
251 <literal>&lt;Namespace&gt;_&lt;Module&gt;_Error</literal>; for example,
252 #GThreadError or #GSpawnError.
253 </para>
254 </listitem>
255 <listitem>
256 <para>
257 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. 
258 </para>
259 </listitem>
260 <listitem>
261 <para>
262 If there's a "generic" or "unknown" error code for unrecoverable errors it
263 doesn't make sense to distinguish with specific codes, it should be called 
264 <literal>&lt;NAMESPACE&gt;_&lt;MODULE&gt;_ERROR_FAILED</literal>, for 
265 example %G_SPAWN_ERROR_FAILED or %G_THREAD_ERROR_FAILED.
266 </para>
267 </listitem>
268 </itemizedlist>
269 </para>
270
271 <para>
272 Summary of rules for use of #GError:
273       <itemizedlist>
274         <listitem>
275           <para>
276            Do not report programming errors via #GError.
277           </para>
278         </listitem>
279
280       <listitem>
281         <para>
282           The last argument of a function that returns an error should be a
283           location where a #GError can be placed (i.e. "#GError** error").  If
284           #GError is used with varargs, the #GError** should be the last
285           argument before the "...".
286         </para>
287       </listitem>
288
289       <listitem>
290         <para>
291           The caller may pass %NULL for the #GError** if they are not interested
292           in details of the exact error that occurred.
293         </para>
294       </listitem>
295
296         <listitem>
297           <para>
298            If %NULL is passed for the #GError** argument, then errors should 
299            not be returned to the caller, but your function should still 
300            abort and return if an error occurs. That is, control flow should
301            not be affected by whether the caller wants to get a #GError.
302           </para>
303         </listitem>
304
305       <listitem>
306         <para>
307           If a #GError is reported, then your function by definition  
308           <emphasis>had a fatal failure and did not complete whatever it was supposed
309             to do</emphasis>. If the failure was not fatal, then you handled it
310           and you should not report it. If it was fatal, then you must report it 
311           and discontinue whatever you were doing immediately.
312         </para>
313       </listitem>
314
315         <listitem>
316           <para>
317           A #GError* must be initialized to %NULL before passing its address to
318           a function that can report errors.
319           </para>
320         </listitem>
321
322         <listitem>
323           <para>
324           "Piling up" errors is always a bug. That is, if you assign a new
325           #GError to a #GError* that is non-%NULL, thus overwriting the previous
326           error, it indicates that you should have aborted the operation instead
327           of continuing. If you were able to continue, you should have cleared
328           the previous error with g_clear_error(). g_set_error() will complain
329           if you pile up errors.
330           </para>
331         </listitem>
332
333
334         <listitem>
335           <para>
336           By convention, if you return a boolean value indicating success 
337           then %TRUE means success and %FALSE means failure. If %FALSE is returned,
338           the error <emphasis>must</emphasis> be set to a non-%NULL value. 
339         </para>
340         </listitem>
341
342
343         <listitem>
344           <para>
345           A %NULL return value is also frequently used to mean that an error
346           occurred.  You should make clear in your documentation whether %NULL is
347           a valid return value in non-error cases; if %NULL is a valid value,
348           then users must check whether an error was returned to see if the
349           function succeeded.
350           </para>
351         </listitem>
352
353         <listitem>
354           <para>
355           When implementing a function that can report errors, you may want to
356           add a check at the top of your function that the error return location
357           is either %NULL or contains a %NULL error
358           (e.g. <literal>g_return_if_fail (error == NULL || *error ==
359           NULL);</literal>).
360           </para>
361         </listitem>
362
363
364 </itemizedlist>
365 </para>
366
367 <!-- ##### SECTION See_Also ##### -->
368 <para>
369
370 </para>
371
372 <!-- ##### STRUCT GError ##### -->
373 <para>
374 The <structname>GError</structname> structure contains 
375 information about an error that has occurred.
376 </para>
377
378 @domain: error domain, e.g. #G_FILE_ERROR.
379 @code: error code, e.g. %G_FILE_ERROR_NOENT.
380 @message: human-readable informative error message.
381
382 <!-- ##### FUNCTION g_error_new ##### -->
383 <para>
384
385 </para>
386
387 @domain: 
388 @code: 
389 @format: 
390 @Varargs: 
391 @Returns: 
392
393
394 <!-- ##### FUNCTION g_error_new_literal ##### -->
395 <para>
396
397 </para>
398
399 @domain: 
400 @code: 
401 @message: 
402 @Returns: 
403
404
405 <!-- ##### FUNCTION g_error_free ##### -->
406 <para>
407
408 </para>
409
410 @error: 
411
412
413 <!-- ##### FUNCTION g_error_copy ##### -->
414 <para>
415
416 </para>
417
418 @error: 
419 @Returns: 
420
421
422 <!-- ##### FUNCTION g_error_matches ##### -->
423 <para>
424
425 </para>
426
427 @error: 
428 @domain: 
429 @code: 
430 @Returns: 
431
432
433 <!-- ##### FUNCTION g_set_error ##### -->
434 <para>
435
436 </para>
437
438 @err: 
439 @domain: 
440 @code: 
441 @format: 
442 @Varargs: 
443
444
445 <!-- ##### FUNCTION g_propagate_error ##### -->
446 <para>
447
448 </para>
449
450 @dest: 
451 @src: 
452
453
454 <!-- ##### FUNCTION g_clear_error ##### -->
455 <para>
456
457 </para>
458
459 @err: <!--
460 Local variables:
461 mode: sgml
462 sgml-parent-document: ("../glib-docs.sgml" "book" "refsect2" "")
463 End:
464 -->
465
466