1 <!-- ##### SECTION Title ##### -->
4 <!-- ##### SECTION Short_Description ##### -->
5 a system for reporting errors
7 <!-- ##### SECTION Long_Description ##### -->
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.
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.)
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.
39 Functions that can fail take a return location for a #GError as their last argument.
41 <informalexample><programlisting>
42 gboolean g_file_get_contents (const gchar *filename,
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>
52 g_file_get_contents ("foo.txt", &contents, NULL, &err);
53 g_assert ((contents == NULL && err != NULL) || (contents != NULL && err == NULL));
56 /* Report error to user, and free error */
57 g_assert (contents == NULL);
58 fprintf (stderr, "Unable to read file: %s\n", err->message);
63 /* Use file contents */
64 g_assert (contents != NULL);
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.
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", &contents, NULL, NULL)) /* ignore errors */
79 /* no error occurred */ ;
82 </programlisting></informalexample>
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->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->message</literal> already contains a filename).
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>
108 foo_open_file (GError **error)
112 fd = open ("file.txt", O_RDONLY);
117 FOO_ERROR, /* error domain */
118 FOO_ERROR_BLAH, /* error code */
119 "Failed to open file: %s", /* error message format string */
126 </programlisting></informalexample>
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>
136 my_function_that_can_fail (GError **err)
138 g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
140 if (!sub_function_that_can_fail (err))
142 /* assert that error was set by the sub-function */
143 g_assert (err == NULL || *err != NULL);
147 /* otherwise continue, no error occurred */
148 g_assert (err == NULL || *err == NULL);
150 </programlisting></informalexample>
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>
159 my_function_that_can_fail (GError **err)
163 g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
166 sub_function_that_can_fail (&tmp_error);
168 if (tmp_error != NULL)
170 /* store tmp_error in err, if err != NULL,
171 * otherwise call g_error_free(<!-- -->) on tmp_error
173 g_propagate_error (err, tmp_error);
177 /* otherwise continue, no error occurred */
179 </programlisting></informalexample>
183 Error pileups are always a bug. For example, this code is incorrect:
184 <informalexample><programlisting>
186 my_function_that_can_fail (GError **err)
190 g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
193 sub_function_that_can_fail (&tmp_error);
194 other_function_that_can_fail (&tmp_error);
196 if (tmp_error != NULL)
198 g_propagate_error (err, tmp_error);
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>
212 my_function_that_can_fail (GError **err)
216 g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
218 sub_function_that_can_fail (NULL); /* ignore errors */
221 other_function_that_can_fail (&tmp_error);
223 if (tmp_error != NULL)
225 g_propagate_error (err, tmp_error);
229 </programlisting></informalexample>
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.
240 Error domains and codes are conventionally named as follows:
244 The error domain is called
245 <literal><NAMESPACE>_<MODULE>_ERROR</literal>, for example
246 %G_SPAWN_ERROR or %G_THREAD_ERROR:
247 <informalexample><programlisting>
248 #define G_SPAWN_ERROR g_spawn_error_quark (<!-- -->)
251 g_spawn_error_quark (void)
253 return g_quark_from_static_string ("g-spawn-error-quark");
255 </programlisting></informalexample>
260 The quark function for the error domain is called <literal><namespace>_<module>_error_quark</literal>, for example g_spawn_error_quark() or %g_thread_error_quark().
265 The error codes are in an enumeration called
266 <literal><Namespace><Module>Error</literal>; for example,
267 #GThreadError or #GSpawnError.
272 Members of the error code enumeration are called <literal><NAMESPACE>_<MODULE>_ERROR_<CODE></literal>, for example %G_SPAWN_ERROR_FORK or %G_THREAD_ERROR_AGAIN.
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><NAMESPACE>_<MODULE>_ERROR_FAILED</literal>, for
280 example %G_SPAWN_ERROR_FAILED or %G_THREAD_ERROR_FAILED.
287 Summary of rules for use of #GError:
291 Do not report programming errors via #GError.
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 "...".
306 The caller may pass %NULL for the #GError** if they are not interested
307 in details of the exact error that occurred.
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.
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.
332 A #GError* must be initialized to %NULL before passing its address to
333 a function that can report errors.
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.
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.
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
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 ==
382 <!-- ##### SECTION See_Also ##### -->
387 <!-- ##### SECTION Stability_Level ##### -->
390 <!-- ##### SECTION Image ##### -->
393 <!-- ##### STRUCT GError ##### -->
395 The <structname>GError</structname> structure contains
396 information about an error that has occurred.
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.
403 <!-- ##### FUNCTION g_error_new ##### -->
415 <!-- ##### FUNCTION g_error_new_literal ##### -->
426 <!-- ##### FUNCTION g_error_new_valist ##### -->
438 <!-- ##### FUNCTION g_error_free ##### -->
446 <!-- ##### FUNCTION g_error_copy ##### -->
455 <!-- ##### FUNCTION g_error_matches ##### -->
466 <!-- ##### FUNCTION g_set_error ##### -->
478 <!-- ##### FUNCTION g_set_error_literal ##### -->
489 <!-- ##### FUNCTION g_propagate_error ##### -->
498 <!-- ##### FUNCTION g_clear_error ##### -->
506 sgml-parent-document: ("../glib-docs.sgml" "book" "refsect2" "")
511 <!-- ##### FUNCTION g_prefix_error ##### -->
521 <!-- ##### FUNCTION g_propagate_prefixed_error ##### -->