-
Notifications
You must be signed in to change notification settings - Fork 0
/
Conditions.Rmd
572 lines (430 loc) · 13.9 KB
/
Conditions.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
# Conditions
```{r Conditions-1, include = FALSE}
source("common.R")
```
Attaching the needed libraries:
```{r Conditions-2, warning=FALSE, message=FALSE}
library(rlang, warn.conflicts = FALSE)
library(testthat, warn.conflicts = FALSE)
```
## Signalling conditions (Exercises 8.2.4)
---
**Q1.** Write a wrapper around `file.remove()` that throws an error if the file to be deleted does not exist.
**A1.** Let's first create a wrapper function around `file.remove()` that throws an error if the file to be deleted does not exist.
```{r Conditions-3}
fileRemove <- function(...) {
existing_files <- fs::file_exists(...)
if (!all(existing_files)) {
stop(
cat(
"The following files to be deleted don't exist:",
names(existing_files[!existing_files]),
sep = "\n"
),
call. = FALSE
)
}
file.remove(...)
}
```
Let's first create a file that we can delete immediately.
```{r Conditions-4}
fs::file_create("random.R")
```
The function should fail if there are any other files provided that don't exist:
```{r Conditions-5, error=TRUE}
fileRemove(c("random.R", "XYZ.csv"))
```
But it does work as expected when the file exists:
```{r Conditions-6}
fileRemove("random.R")
```
---
**Q2.** What does the `appendLF` argument to `message()` do? How is it related to `cat()`?
**A2.** As mentioned in the docs for `message()`, `appendLF` argument decides:
> should messages given as a character string have a newline appended?
- If `TRUE` (default value), a final newline is regarded as part of the message:
```{r Conditions-7}
foo <- function(appendLF) {
message("Beetle", appendLF = appendLF)
message("Juice", appendLF = appendLF)
}
foo(appendLF = TRUE)
```
- If `FALSE`, messages will be concatenated:
```{r Conditions-8}
foo <- function(appendLF) {
message("Beetle", appendLF = appendLF)
message("Juice", appendLF = appendLF)
}
foo(appendLF = FALSE)
```
On the other hand, `cat()` converts its arguments to character vectors and concatenates them to a single character vector by default:
```{r Conditions-9}
foo <- function() {
cat("Beetle")
cat("Juice")
}
foo()
```
In order to get `message()`-like default behavior for outputs, we can set `sep = "\n"`:
```{r Conditions-10}
foo <- function() {
cat("Beetle", sep = "\n")
cat("Juice", sep = "\n")
}
foo()
```
---
## Handling conditions (Exercises 8.4.5)
---
**Q1.** What extra information does the condition generated by `abort()` contain compared to the condition generated by `stop()` i.e. what's the difference between these two objects? Read the help for `?abort` to learn more.
```{r Conditions-11, eval = FALSE}
catch_cnd(stop("An error"))
catch_cnd(abort("An error"))
```
**A1.** Compared to `base::stop()`, `rlang::abort()` contains two additional pieces of information:
- `trace`: A traceback capturing the sequence of calls that lead to the current function
- `parent`: Information about another condition used as a parent to create a chained condition.
```{r Conditions-12}
library(rlang)
stopInfo <- catch_cnd(stop("An error"))
abortInfo <- catch_cnd(abort("An error"))
str(stopInfo)
str(abortInfo)
```
---
**Q2.** Predict the results of evaluating the following code
```{r Conditions-13, eval = FALSE}
show_condition <- function(code) {
tryCatch(
error = function(cnd) "error",
warning = function(cnd) "warning",
message = function(cnd) "message",
{
code
NULL
}
)
}
show_condition(stop("!"))
show_condition(10)
show_condition(warning("?!"))
show_condition({
10
message("?")
warning("?!")
})
```
**A2.** Correctly predicted 😉
The first three pieces of code are straightforward:
```{r Conditions-14, warning=TRUE,message=TRUE,error=TRUE}
show_condition <- function(code) {
tryCatch(
error = function(cnd) "error",
warning = function(cnd) "warning",
message = function(cnd) "message",
{
code
NULL
}
)
}
show_condition(stop("!"))
show_condition(10)
show_condition(warning("?!"))
```
The last piece of code is the challenging one and it illustrates how `tryCatch()` works. From its docs:
> When several handlers are supplied in a single tryCatch then the first one is considered more recent than the second.
```{r Conditions-15, warning=TRUE,message=TRUE,error=TRUE}
show_condition({
10
message("?")
warning("?!")
})
```
---
**Q3.** Explain the results of running this code:
```{r Conditions-16}
withCallingHandlers(
message = function(cnd) message("b"),
withCallingHandlers(
message = function(cnd) message("a"),
message("c")
)
)
```
**A3.** The surprising part of this output is the `b` before the last `c`.
This happens because the inner calling handler doesn't handle the message, so it bubbles up to the outer calling handler.
---
**Q4.** Read the source code for `catch_cnd()` and explain how it works.
**A4.** Let's look at the source code for `catch_cnd()`:
```{r Conditions-17}
rlang::catch_cnd
```
As mentioned in the function docs:
> This is a small wrapper around `tryCatch()` that captures any condition signalled while evaluating its argument.
The `classes` argument allows a character vector of condition classes to catch, and the complex tidy evaluation generates the necessary condition (if there is any; otherwise `NULL`).
```{r Conditions-18, error=TRUE}
catch_cnd(10)
catch_cnd(abort(message = "an error", class = "class1"))
```
---
**Q5.** How could you rewrite `show_condition()` to use a single handler?
**A5.** The source code for `rlang::catch_cond()` gives us a clue as to how we can do this.
Conditions also have a `class` attribute, and we can use it to determine which handler will match the condition.
```{r Conditions-19}
show_condition2 <- function(code) {
tryCatch(
condition = function(cnd) {
if (inherits(cnd, "error")) {
return("error")
}
if (inherits(cnd, "warning")) {
return("warning")
}
if (inherits(cnd, "message")) {
return("message")
}
},
{
code
NULL
}
)
}
```
Let's try this new version with the examples used for the original version:
```{r Conditions-20}
show_condition2(stop("!"))
show_condition2(10)
show_condition2(warning("?!"))
show_condition2({
10
message("?")
warning("?!")
})
```
---
## Custom conditions (Exercises 8.5.4)
---
**Q1.** Inside a package, it's occasionally useful to check that a package is installed before using it. Write a function that checks if a package is installed (with `requireNamespace("pkg", quietly = FALSE))` and if not, throws a custom condition that includes the package name in the metadata.
**A1.** Here is the desired function:
```{r Conditions-21, error=TRUE}
abort_missing_package <- function(pkg) {
msg <- glue::glue("Problem loading `{pkg}` package, which is missing and must be installed.")
abort("error_missing_package",
message = msg,
pkg = pkg
)
}
check_if_pkg_installed <- function(pkg) {
if (!requireNamespace(pkg, quietly = TRUE)) {
abort_missing_package(pkg)
}
TRUE
}
check_if_pkg_installed("xyz123")
check_if_pkg_installed("dplyr")
```
For a reference, also see the source code for following functions:
- `rlang::is_installed()`
- `insight::check_if_installed()`
---
**Q2.** Inside a package you often need to stop with an error when something is not right. Other packages that depend on your package might be tempted to check these errors in their unit tests. How could you help these packages to avoid relying on the error message which is part of the user interface rather than the API and might change without notice?
**A2.** As an example, let's say that another package developer wanted to use the `check_if_pkg_installed()` function that we just wrote.
So the developer using it in their own package can write a unit test like this:
```{r Conditions-22}
expect_error(
check_if_pkg_installed("xyz123"),
"Problem loading `xyz123` package, which is missing and must be installed."
)
```
To dissuade developers from having to rely on error messages to check for errors, we can instead provide a custom condition, which can be used for unit testing instead:
```{r Conditions-23}
e <- catch_cnd(check_if_pkg_installed("xyz123"))
inherits(e, "error_missing_package")
```
So that the unit test could be:
```{r Conditions-24}
expect_s3_class(e, "error_missing_package")
```
This test wouldn't fail even if we decided to change the exact message.
---
## Applications (Exercises 8.6.6)
---
**Q1.** Create `suppressConditions()` that works like `suppressMessages()` and `suppressWarnings()` but suppresses everything. Think carefully about how you should handle errors.
**A1.** To create the desired `suppressConditions()`, we just need to create an equivalent of `suppressWarnings()` and `suppressMessages()` for errors. To suppress the error message, we can handle errors within a `tryCatch()` and return the error object invisibly:
```{r Conditions-25}
suppressErrors <- function(expr) {
tryCatch(
error = function(cnd) invisible(cnd),
expr
)
}
suppressConditions <- function(expr) {
suppressErrors(suppressWarnings(suppressMessages(expr)))
}
```
Let's try out and see if this works as expected:
```{r Conditions-26}
suppressConditions(1)
suppressConditions({
message("I'm messaging you")
warning("I'm warning you")
})
suppressConditions({
stop("I'm stopping this")
})
```
All condition messages are now suppressed, but note that if we assign error object to a variable, we can still extract useful information for debugging:
```{r Conditions-27}
e <- suppressConditions({
stop("I'm stopping this")
})
e
```
---
**Q2.** Compare the following two implementations of `message2error()`. What is the main advantage of `withCallingHandlers()` in this scenario? (Hint: look carefully at the traceback.)
```{r Conditions-28}
message2error <- function(code) {
withCallingHandlers(code, message = function(e) stop(e))
}
message2error <- function(code) {
tryCatch(code, message = function(e) stop(e))
}
```
**A2.** With `withCallingHandlers()`, the condition handler is called from the signaling function itself, and, therefore, provides a more detailed call stack.
```{r Conditions-29, error = TRUE, eval = FALSE}
message2error1 <- function(code) {
withCallingHandlers(code, message = function(e) stop("error"))
}
message2error1({
1
message("hidden error")
NULL
})
#> Error in (function (e) : error
traceback()
#> 9: stop("error") at #2
#> 8: (function (e)
#> stop("error"))(list(message = "hidden error\n",
#> call = message("hidden error")))
#> 7: signalCondition(cond)
#> 6: doWithOneRestart(return(expr), restart)
#> 5: withOneRestart(expr, restarts[[1L]])
#> 4: withRestarts({
#> signalCondition(cond)
#> defaultHandler(cond)
#> }, muffleMessage = function() NULL)
#> 3: message("hidden error") at #1
#> 2: withCallingHandlers(code,
#> message = function(e) stop("error")) at #2
#> 1: message2error1({
#> 1
#> message("hidden error")
#> NULL
#> })
```
With `tryCatch()`, the signalling function terminates when a condition is raised, and so it doesn't provide as detailed call stack.
```{r Conditions-30, error = TRUE, eval = FALSE}
message2error2 <- function(code) {
tryCatch(code, message = function(e) (stop("error")))
}
message2error2({
1
stop("hidden error")
NULL
})
#> Error in value[[3L]](cond) : error
traceback()
#> 6: stop("error") at #2
#> 5: value[[3L]](cond)
#> 4: tryCatchOne(expr, names, parentenv, handlers[[1L]])
#> 3: tryCatchList(expr, classes, parentenv, handlers)
#> 2: tryCatch(code, message = function(e) (stop("error"))) at #2
#> 1: message2error2({
#> 1
#> message("hidden error")
#> NULL
#> })
```
---
**Q3.** How would you modify the `catch_cnds()` definition if you wanted to recreate the original intermingling of warnings and messages?
**A3.** Actually, you won't have to modify anything about the function defined in the chapter, since it supports this out of the box.
So nothing additional to do here^[The best kind of exercise there is!]! 😅
```{r Conditions-31}
catch_cnds <- function(expr) {
conds <- list()
add_cond <- function(cnd) {
conds <<- append(conds, list(cnd))
cnd_muffle(cnd)
}
withCallingHandlers(
message = add_cond,
warning = add_cond,
expr
)
conds
}
catch_cnds({
inform("a")
warn("b")
inform("c")
})
```
---
**Q4.** Why is catching interrupts dangerous? Run this code to find out.
```{r Conditions-32, eval = FALSE}
bottles_of_beer <- function(i = 99) {
message(
"There are ",
i,
" bottles of beer on the wall, ",
i,
" bottles of beer."
)
while (i > 0) {
tryCatch(
Sys.sleep(1),
interrupt = function(err) {
i <<- i - 1
if (i > 0) {
message(
"Take one down, pass it around, ",
i,
" bottle",
if (i > 1) "s",
" of beer on the wall."
)
}
}
)
}
message(
"No more bottles of beer on the wall, ",
"no more bottles of beer."
)
}
```
**A4.** Because this function catches the `interrupt` and there is no way to stop `bottles_of_beer()`, because the way you would usually stop it by using `interrupt`!
```{r Conditions-33, eval=FALSE}
bottles_of_beer()
#> There are 99 bottles of beer on the wall, 99 bottles of beer.
#> Take one down, pass it around, 98 bottles of beer on the wall.
#> Take one down, pass it around, 97 bottles of beer on the wall.
#> Take one down, pass it around, 96 bottles of beer on the wall.
#> Take one down, pass it around, 95 bottles of beer on the wall.
#> Take one down, pass it around, 94 bottles of beer on the wall.
#> Take one down, pass it around, 93 bottles of beer on the wall.
#> Take one down, pass it around, 92 bottles of beer on the wall.
#> Take one down, pass it around, 91 bottles of beer on the wall.
#> ...
```
In RStudio IDE, you can snap out of this loop by terminating the R session.
This shows why catching `interrupt` is dangerous and can result in poor user experience.
---
## Session information
```{r Conditions-34}
sessioninfo::session_info(include_base = TRUE)
```