Debian Codegraph @

crt/aws-c-common/docs/error-handling.md

raw symbols SCIP
1 # Error Handling
2
3 ## Basics
4
5 Every function that returns an `int` type returns either `AWS_OP_SUCCESS` (0) on success, or `AWS_OP_ERR` (-1) on failure.
6
7 ```c
8 /* Example of function returning int type.
9 * Returns AWS_OP_SUCCESS (0) on success.
10 * Returns AWS_OP_ERR (-1) on failure. */
11 int aws_do_something(...);
12 ```
13
14 And every function that returns a pointer, returns `NULL` on failure.
15
16 ```c
17 /* Example of function returning a pointer type.
18 * Returns a valid pointer on success.
19 * Returns NULL on failure. */
20 struct aws_thing *aws_thing_new(...);
21 ```
22
23 After a function fails, you call `aws_last_error()` to retrieve the actual error code. You can get strings for each error code via:
24 * `const char *aws_error_name(int error_code)` for the enum name
25 * e.g. `34` -> `"AWS_ERROR_INVALID_ARGUMENT"`
26
27 * `const char *aws_error_str(int error_code)` for the English description
28 * e.g. `34` -> `"An invalid argument was passed to a function."`
29
30 This error code is stored in a thread-local variable.
31
32 If you're authoring a function that needs to fail, you MUST call `aws_raise_error(error_code)` to set that thread-local error code before returning `AWS_OP_ERR` or `NULL`.
33
34 ### Design
35
36 We do error handling this way because that's how other C libs do it. For example, [fopen()](https://en.cppreference.com/w/c/io/fopen) returns a pointer and if it's `NULL` you check `errno` to find out why. This way, functions can simply return a pointer, without polluting their function signature with confusing out-params. For consistency, we had other functions use thread-local variables as well, returning `AWS_OP_ERR` (-1) instead of returning the actual error code.
37
38 While this design pattern makes for graceful looking user code, it is very easy to make mistakes in implementation code, if you forget to call `aws_raise_error()` in all possible failure branches. Hence, this guide...
39
40 ### Catching Errors
41
42 Error handling in a toy application might look like:
43 ```c
44 /* For functions that return a pointer, NULL means failure */
45 struct aws_thing *thing = aws_thing_new(...);
46 if (thing == NULL) {
47 int error_code = aws_last_error();
48 printf("Failed to create thing: %s\n", aws_error_str(error_code));
49 exit(error_code);
50 }
51
52 /* For functions that return an int, AWS_OP_ERR means failure */
53 if (aws_thing_do_something_that_may_fail(thing, ...) == AWS_OP_ERR) {
54 int error_code = aws_last_error();
55 printf("Failed to do something: %s\n", aws_error_str(error_code));
56 exit(error_code);
57 }
58
59 /* You'll also see lots of code that doesn't explicitly compare the return value
60 * against `AWS_OP_ERR` or `AWS_OP_SUCCESS`. Since AWS_OP_SUCCESS is zero,
61 * it's "falsey", so the if branch is only taken on error. */
62 if (aws_thing_do_something_that_may_fail(thing, ...)) {
63 int error_code = aws_last_error();
64 printf("Failed to do something: %s\n", aws_error_str(error_code));
65 exit(error_code);
66 }
67
68 /* DO NOT DO THIS */
69 aws_thing_do_something_that_may_fail(thing, ...); /* BAD */
70 if (aws_last_error() != 0) { /* BAD */
71 /* This code assumes something went wrong because the thread-local
72 * error code is non-zero. BUT nobody ever bothers to clear the
73 * thread-local error code! It could be a stale value from earlier
74 * in the program, and that error might have been handled just fine.
75 * You should only check aws_last_error() after checking that a function
76 * explicitly returned `AWS_OP_ERR` or `NULL` to indicate failure. */
77 printf("I assume previous function call just failed");
78 exit(aws_last_error());
79 }
80 ```
81
82 ### Raising Errors
83
84 When writing functions that may fail, you MUST ensure `aws_raise_error()` is called, to set that thread-local error code, before you ultimately return `NULL` or `AWS_OP_ERR`. DO NOT accidentally return the error-code itself.
85
86 ```c
87 /* Sample for function that returns pointer type, where NULL means failure */
88 struct aws_thing *aws_thing_new(struct aws_allocator *allocator, uint32_t num_shinies) {
89 if (num_shinies > AWS_NUM_SHINIES_MAX) {
90 /* Set thread-local error code */
91 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
92 /* Return NULL to indicate failure */
93 return NULL;
94 }
95
96 struct aws_thing *thing = aws_mem_calloc(allocator, 1, sizeof(struct aws_thing));
97 thing->num_shinies = num_shinies;
98
99 /* Returning a valid pointer means success */
100 return thing;
101 }
102
103 /* Sample for function that returns int, where AWS_OP_ERR(-1) means failure */
104 int aws_sub_u64_checked(uint64_t a, uint64_t b, uint64_t *result) {
105 if (a < b) {
106 aws_raise_error(AWS_ERROR_OVERFLOW_DETECTED);
107 return AWS_OP_ERR;
108
109 /* You can also do: return aws_raise_error(AWS_ERROR_OVERFLOW_DETECTED);
110 * aws_raise_error() always return AWS_OP_ERR, so you can call it on
111 * the same line as return, if your function returns int. */
112 }
113
114 *result = a - b;
115 return AWS_OP_SUCCESS;
116 }
117
118
119 /* DO NOT DO THIS */
120 int aws_sub_u64_checked(uint64_t a, uint64_t b, uint64_t *result) {
121 if (a < b)
122 /* BAD: Failed to set thread-local error code. */
123 return AWS_OP_ERR;
124 ...
125
126 /* DO NOT DO THIS */
127 int aws_sub_u64_checked(uint64_t a, uint64_t b, uint64_t *result) {
128 if (a < b)
129 /* BAD: Failed to set thread-local error code.
130 * BAD: Accidentally returned error code, but should return AWS_OP_ERR. */
131 return AWS_ERROR_OVERFLOW_DETECTED;
132 ...
133 ```
134
135 If you're writing a function that may fail, and it needs to call other `aws_` functions that may fail, you can assume the other function set the error code explaining why.
136
137 ```c
138 int aws_my_new_function(...) {
139 if (aws_some_other_thing_that_may_fail(...) != AWS_OP_SUCCESS) {
140 /* Here, it's OK not to call aws_raise_error().
141 * The other aws_ function already set the thread-local error code
142 * that we want the user to see. */
143 return AWS_OP_ERR;
144 }
145 ...
146 ```
147
148 But beware that the thread-local error code can change. You may want to store it (e.g. `int error_code = aws_last_error();`) if you need to do a lot of other stuff between the error originally occurring, and your function finally returning `AWS_OP_ERR`. In general, simple cleanup and logging functions won't change the error code. But if you're doing more than that, may as well be safe and store it. Here's an example:
149 ```c
150 ...
151 if (aws_some_other_thing_that_may_fail(...) != AWS_OP_SUCCESS) {
152 /* Preserve error code */
153 int error_code = aws_last_error();
154
155 ...many more lines of code...
156 ...maybe invoking user callbacks, where anything can happen...
157 ...and maybe thread-local error code gets changed...
158
159 /* Re-raise, ensuring caller gets the error code you intend */
160 return aws_raise_error(error_code);
161 }
162 ```
163
164 ### Error codes in callbacks
165
166 For asynchronous APIs, where results are delivered via callback, error codes are delivered by their actual value. A callback function might look like:
167 ```c
168 void on_some_async_operation_complete(int error_code, void *user_data) {
169 if (error_code != 0) {
170 printf("Operation failed: %s\n", aws_error_str(error_code));
171 ...
172 ```
173
174 The thread-local error code variable is not used with callbacks. `AWS_OP_ERR` and `AWS_OP_SUCCESS` are not used. DO NOT call `aws_raise_error()` before invoking a callback. DO NOT call `aws_last_error()` within a callback to check for error.
175
176 ## Best Practices
177
178 Error handling is extra difficult in C, because C doesn't have automatic destructors or garbage collection. If you need to do several things in sequence, and the last thing fails, you need to manually undo all previous steps.
179
180 We suggest keeping things as simple and maintainable as we can get away with.
181
182 Our style has evolved with time, and you'll find lots of old code violating these rules, but here are best practices.
183
184 ### If a function can't fail, make it void
185
186 Don't return `int` "just in case it might fail someday" or "for consistency with other functions".
187
188 This is especially important for low-level datastructure APIs, or any function that cleans up or destroys something.
189
190 Imagine there's some "clean up" function that needs to use your function, and your function returns `int`. What is that clean up function supposed to do? Try to handle the error? How? Should it stop even trying to clean up? Leak memory?
191
192 If your function creates some complex stateful class, that takes lots of parameters, and can't currently fail, but you can totally imagine a future where it can, then yeah give it an API where it might fail. But for simple stuff that's just allocating: no.
193
194 ### Memory Allocation Cannot Fail
195
196 Don't write code that tries to handle Out Of Memory (OOM). `aws_mem_acquire()` and `aws_mem_calloc()` will never return `NULL`, they will simply abort if the OS fails to allocate.
197
198 For the first few months of aws-c development, we tried to handle Out Of Memory. Lots of code was written that tried to deal with this; little of it was ever tested. In the end we decided it wasn't worth the effort. Swift and Rust just abort if you push into a vector and it can't expand. We should too. Now, `aws_allocator` will abort before it ever returns `NULL`.
199
200 Unfortunately, after making this change we didn't go back and simplify APIs that could no longer fail, because it would be a large breaking change. So functions like `aws_hash_table_put()` return `int` but it's always `AWS_OP_SUCCESS` and you should never bother checking it. It sucks, but you just have to "know" which errors should or shouldn't be checked for. It's generally just our older datastructure APIs that suffer from this (e.g. aws_byte_buf, aws_array_list, aws_hash_table). If you initialized these with an allocator, so they can grow dynamically, then they can't fail. But if you initialized them with a fixed size, or no allocator, you should still check for errors. For pretty much all other APIs, you must still check for errors.
201
202 Also, we didn't proactively remove error-handling code where the errors couldn't happen anymore. But if you're ever editing such code, do please simplify it along with your changes! Also, if you find an old function that can't fail, but its docs say it may, update the docs!
203
204 ### Don't try to handle NULL (except in destructors)
205
206 If a function doesn't expect `NULL`, then don't try to handle `NULL`.
207
208 Feel free to add `AWS_ASSERT(some_pointer);` if you want your code to be clear about its refusal to deal with NULL.
209
210 Imagine you tried to handle `NULL`, then functions then function that could be `void` now must return `int`, just in case `NULL` is passed in and they can't do anything! Now you have a function with an error code, but it can't possible fail in working code. But users wonder whether or not they should be checking for failure from this function... and maybe stop checking for errors on other functions that *can* fail randomly... if it's a mess. Also, be honest, you're never going to add tests for all that error handling code.
211
212 One big exception is destructors (i.e. `clean_up()`, `destroy()`, `release()`). We'll touch on this later, but to make error-handling code as simple as possible, we want it to be safe to call destructor functions whether or not the thing was ever successfully created.
213
214 ### AWS_ASSERT() vs AWS_FATAL_ASSERT() vs aws_raise_error()
215
216 How do you choose when to assert, vs real error handling? Asserts will simply abort the program, so only use them for detecting internal bugs. We *never* want users from Java or Python to hit an assert. So things like validating a number's value should be real error checks, because the number might come from a Java user.
217
218 `AWS_ASSERT()` does nothing in Release builds, it only checks in Debug. Use this for basic sanity checks that NULL isn't being passed into a function, or as a comment to future programmers "don't worry, this can't possibly be true right now", or to do an expensive check you don't want happening in Release builds. Note that most language bindings (e.g. _awscrt.so in aws-crt-python) are *never* built in Debug.
219
220 `AWS_FATAL_ASSERT()` still runs in Release builds. Use this to catch bugs that might occur in language binding code (which is seldom built in Debug), or for internal bugs you worry are too complex to encounter in a Debug build.
221
222 Use `aws_raise_error()` (real error handling) for everything else.
223
224 ### init() / clean_up() example
225
226 Here's an example, with an "init / clean_up" style struct, where any initialization step may fail, and we'd need to undo the previous steps:
227 ```c
228 int aws_thing_init(struct aws_thing *thing) {
229 /* First, zero things out, in case memory was uninitialized.
230 * That way we can safely call clean_up() on each member,
231 * even if we didn't fully initialize everything.*/
232 AWS_ZERO_STRUCT(*thing);
233
234 if (aws_complex_part_1_init(&thing->part_1) != AWS_OP_SUCCESS) {
235 /* Prefer early-out patterns, vs deeply embedded if-branches */
236 goto error;
237 }
238
239 if (aws_complex_part_2_init(&thing->part_2) != AWS_OP_SUCCESS) {
240 /* goto is fine in C */
241 goto error;
242 }
243
244 if (aws_complex_part_3_init(&thing->part_3) != AWS_OP_SUCCESS) {
245 goto error;
246 }
247
248 return AWS_OP_SUCCESS;
249
250 error:
251 /* Just call the clean_up() function, rather than repeating
252 * the code that cleans up individual members */
253 aws_thing_clean_up(thing);
254
255 /* Note: we didn't set thread-local error code before returning AWS_OP_ERR,
256 * because we assume it was already set by the aws_complex_part_N_init()
257 * failure that led us here */
258 return AWS_OP_ERR;
259 }
260
261 void aws_thing_clean_up(struct aws_thing *thing) {
262 /* It's safe to try and clean up aws_ types, even if they were never
263 * initialized. We build all our "destructors" to be idempotent
264 * and safe to call on zeroed-out memory.
265 * This lets us have nice clean simple clean up code like so: */
266 aws_complex_part_3_clean_up(&thing->part_3);
267 aws_complex_part_2_clean_up(&thing->part_2);
268 aws_complex_part_1_clean_up(&thing->part_1);
269
270 /* Finally, zero things out so the clean_up() is idempotent */
271 AWS_ZERO_STRUCT(*thing);
272 }
273 ```
274
275 And here are some ways NOT to do it:
276 ```c
277 /* DO NOT DO THIS (each failed step tries to clean up previous steps) */
278 int aws_thing_init(struct aws_thing *thing) {
279 AWS_ZERO_STRUCT(*thing);
280
281 if (aws_complex_part_1_init(&thing->part_1) != AWS_OP_SUCCESS) {
282 return AWS_OP_ERR;
283 }
284
285 if (aws_complex_part_2_init(&thing->part_2) != AWS_OP_SUCCESS) {
286 aws_complex_part_1_clean_up(&thing->part_1);
287 return AWS_OP_ERR;
288 }
289
290 if (aws_complex_part_3_init(&thing->part_3) != AWS_OP_SUCCESS) {
291 /* BAD: If clean up code is in so many places, and subtly different
292 * each time, it's really easy to make a mistake. */
293 aws_complex_part_2_clean_up(&thing->part_2);
294 aws_complex_part_1_clean_up(&thing->part_1);
295 return AWS_OP_ERR;
296 }
297
298 return AWS_OP_SUCCESS;
299 }
300
301 /* DO NOT DO THIS (multiple goto labels) */
302 int aws_thing_init(struct aws_thing *thing) {
303 AWS_ZERO_STRUCT(*thing);
304
305 if (aws_complex_part_1_init(&thing->part_1) != AWS_OP_SUCCESS) {
306 return AWS_OP_ERR;
307 }
308
309 if (aws_complex_part_2_init(&thing->part_2) != AWS_OP_SUCCESS) {
310 goto clean_up_part_1;
311 }
312
313 if (aws_complex_part_3_init(&thing->part_3) != AWS_OP_SUCCESS) {
314 /* BAD: having multiple goto labels is a copy/paste bug waiting to happen */
315 goto clean_up_part_2;
316 }
317
318 return AWS_OP_SUCCESS;
319
320 clean_up_part_2:
321 /* BAD: if you try to clean up individual parts, you repeat code that's
322 * already in clean_up(). You risk bugs where someone adds a new member,
323 * and forgets to clean it up from here too. */
324 aws_complex_part_2_clean_up(&thing->part_2);
325 clean_up_part_1:
326 aws_complex_part_1_clean_up(&thing->part_1);
327 return AWS_OP_ERR;
328 }
329
330 /* DO NOT DO THIS (deep if statements) */
331 int aws_thing_init(struct aws_thing *thing) {
332 AWS_ZERO_STRUCT(*thing);
333
334 if (aws_complex_part_1_init(&thing->part_1) == AWS_OP_SUCCESS) {
335 if (aws_complex_part_2_init(&thing->part_2) == AWS_OP_SUCCESS) {
336 if (aws_complex_part_3_init(&thing->part_3) == AWS_OP_SUCCESS) {
337 /* BAD: You end up with most of your code indented
338 * 5+ levels deep. Adding more checks results in a
339 * huge diff as everything get indented even more.
340 * It actually doesn't look so bad in this example,
341 * but believe me it sucks in real life. */
342 return AWS_OP_SUCCESS;
343 }
344 aws_complex_part_2_clean_up(&thing->part_2);
345 }
346 aws_complex_part_1_clean_up(&thing->part_1);
347 }
348
349 return AWS_OP_ERR;
350 }
351 ```
352
353 ### new() / destroy() example
354
355 Here's an example that returns a pointer, and does a bit more:
356 ```c
357 struct aws_thing *aws_thing_new(struct aws_allocator *alloc,
358 const struct aws_thing_options *options) {
359 /* DO NOT do real error-checking for NULL args, that way lies madness.
360 * You MAY do these debug-only statements that kill the program */
361 AWS_ASSERT(alloc);
362 AWS_ASSERT(options);
363
364 /* Before creating anything, do real error checking on values that
365 * might come down from language bindings. Not NULL checks, but other
366 * more subtle stuff */
367 if (options->timeout_ms > AWS_THING_TIMEOUT_MS_MAX) {
368 /* Log the exact issue, since "invalid argument" is vague
369 * when there are lots of arguments */
370 AWS_LOGF_ERROR(..., "timeout_ms has invalid value");
371 /* Set thread-local error code before returning NULL */
372 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
373 return NULL;
374 }
375
376 /* Use aws_mem_calloc() to get memory that's already zeroed-out. This
377 * reduces bugs where you forget to initialize a member */
378 struct aws_thing *thing = aws_mem_calloc(alloc, 1, sizeof(struct aws_thing));
379
380 /* Don't need to check if thing == NULL because allocation can't fail */
381
382 /* Set allocator (and other things that can't possibly fail) first, so we
383 * can use the destroy() function to clean up if anything else goes wrong */
384 thing->alloc = alloc;
385 thing->timeout_ms = options->timeout_ms;
386
387 if (aws_complex_part_1_init(&thing->part_1) != AWS_OP_SUCCESS) {
388 goto error;
389 }
390
391 if (aws_complex_part_2_init(&thing->part_2) != AWS_OP_SUCCESS) {
392 goto error;
393 }
394
395 if (aws_complex_part_3_init(&thing->part_3) != AWS_OP_SUCCESS) {
396 goto error;
397 }
398
399 return thing;
400
401 error:
402 aws_thing_destroy(thing);
403
404 /* Note: we didn't set thread-local error code before returning NULL,
405 * because we assume it was already set by the aws_complex_part_N_init()
406 * failure that led us here */
407 return NULL;
408 }
409
410 void aws_thing_destroy(struct aws_thing *thing) {
411 /* "destructor" functions are the only place we check for NULL, so user
412 * can naively call it, whether or not it was successfully created */
413 if (thing == NULL) {
414 return;
415 }
416
417 aws_complex_part_3_clean_up(&thing->part_3);
418 aws_complex_part_2_clean_up(&thing->part_2);
419 aws_complex_part_1_clean_up(&thing->part_1);
420
421 aws_mem_release(thing->alloc, thing);
422 }
423 ```
424
425 ## In Hindsight
426
427 It's too late to change any of this, but here's graebm's personal opinion for anyone starting down a similar path.
428
429 ### thread-local error codes are too hard
430
431 IMHO it's too easy to make a mistake, and forget to `aws_raise_error()` before returning `AWS_OP_ERR`. When this happens, the user gets a nonsense value from `aws_last_error()`, and it's very hard to know what is actually failing.
432
433 IMHO we should have done something like Rust's [std::result<T, E>](https://doc.rust-lang.org/std/result/), Swift's [Result<Success,Failure>](https://developer.apple.com/documentation/swift/result), and C++'s [std::expected<T,E>](https://en.cppreference.com/w/cpp/utility/expected). If we returned errors by value, we wouldn't have bugs where we forgot to set `aws_raise_error()`, or bugs where `aws_last_error()` was accidentally overwritten. C doesn't have generics, but you can create something like them using macros (see [future.h](https://github.com/awslabs/aws-c-io/blob/7e75f17400ca2cfdc296865b9c2b10323f49a9c5/include/aws/io/future.h#L30)), or just write:
434 ```c
435 struct aws_thing_result {
436 struct aws_thing *ok;
437 int err;
438 };
439
440 struct aws_thing_result aws_thing_new(...);
441 ```
442
443 And functions that don't return pointers can just return the error code by value:
444 ```
445 /* returns AWS_OK (0) on success, or the error code */
446 int aws_thing_do_something_that_may_fail(...);
447 ```
448
449 ### int error codes lose information
450
451 Exceptions in other languages can carry a lot more information than int error codes. If a Java exception occurs within a C callback, all the information from that callback must be thrown out. The Java user ultimately sees something less-than-useful like AWS_ERROR_HTTP_CALLBACK_FAILURE. We must tell the Java user to enable CRT logging to see what's actually going wrong. It's not idiomatic.
452
453 IMHO errors shouldn't just be ints, they should carry lots more information (e.g. custom message, chain of caused_by, is_retryable, etc). But this would make them "heavier", so we wouldn't want to use them somewhere performance sensitive, like querying a hash table. We could reserve "rich" errors for the APIs that language bindings call directly. We might even be able to create a Java exception chain where some of those came from our "rich" errors.