forked from Tazinho/Advanced-R-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2-08-Conditions.Rmd
executable file
·380 lines (303 loc) · 12.8 KB
/
2-08-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
```{r, include=FALSE}
source("common.R")
```
# Conditions
## Signalling conditions
1. __[Q]{.Q}__: Write a wrapper around `file.remove()` that throws an error if the file to be deleted does not exist.
__[A]{.solved}__: We have several options here. However, we prefer the following solution for its clarity and simplicity:
```{r, error = TRUE}
file_remove_strict <- function(path) {
if (!file.exists(path)) {
stop("Can't delete '", path, "' because it doesn't exist.", call. = FALSE)
}
file.remove(path)
}
# Test
saveRDS(iris, "iris.rds")
file_remove_strict("iris.rds")
file_remove_strict("iris.rds")
```
<!-- HW: I don't think using ... here is a good idea because then you `file.exists()` will return a vector, and you'll need to think a lot more about the error message -->
2. __[Q]{.Q}__: What does the `appendLF` argument to `message()` do? How is it related to `cat()`?
__[A]{.solved}__: The `appendLF` argument automatically appends a new line to the message. Let's illustrate this behaviour with a small example function:
```{r, eval=FALSE}
multiline_msg <- function(appendLF = TRUE) {
message("first", appendLF = appendLF)
cat("second")
cat("third")
}
multiline_msg(appendLF = TRUE)
#> first
#> secondthird
multiline_msg(appendLF = FALSE)
#> first line
#> secondthird
```
Compared to `cat()`, `message()` adds the newl line for you.
## Handling conditions
1. __[Q]{.Q}__: 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, include=FALSE}
library(rlang)
catch_cnd(stop("An error"))
catch_cnd(abort("An error"))
```
__[A]{.solved}__: In contrast to `stop()`, which contains the call, `abort()` stores the whole backtrace generated by `rlang::trace_back()`. This is a lot of extra data!
```{r}
str(catch_cnd(stop("An error")))
str(catch_cnd(abort("An error")))
```
2. __[Q]{.Q}__: Predict the results of evaluating the following code
```{r}
show_condition <- function(code) {
tryCatch(
error = function(cnd) "error",
warning = function(cnd) "warning",
message = function(cnd) "message",
{
code
NULL
}
)
}
```
```{r, eval = FALSE}
show_condition(stop("!"))
show_condition(10)
show_condition(warning("?!"))
show_condition({
10
message("?")
warning("?!")
})
```
__[A]{.solved}__: The first three examples are straightforward:
```{r}
show_condition(stop("!")) # stop raises an error
show_condition(10) # no condition is signalled
show_condition(warning("?!")) # warning raises a warning
```
The last example is the most interesting and makes us aware of the exiting qualities of `tryCatch()`, it will terminate the evaluation of the code as soon as it is called.
```{r}
show_condition({
10
message("?")
warning("?!")
})
```
3. __[Q]{.Q}__: Explain the results of running this code:
```{r}
withCallingHandlers( # (1)
message = function(cnd) message("b"),
withCallingHandlers( # (2)
message = function(cnd) message("a"),
message("c")
)
)
```
__[A]{.solved}__: It's a little tricky to untangle the flow here:
First, `message("c")` is run, and it's caught by (1). It then calls `message("a")`, which is caught by (2), which calls `message("b")`. `message("b")` isn't caught by anything, so we see a `b` on the console, followed by `a`. But why do we get another `b` before we see `c`? That's because we haven't handled the message, so it bubbles up to the outer calling handler.
4. __[Q]{.Q}__: Read the source code for `catch_cnd()` and explain how it works. At the time the book was written, the source for `catch_cnd()` was a little simpler:
```{r}
catch_cnd <- function(expr) {
tryCatch(
condition = function(cnd) cnd,
{
force(expr)
return(NULL)
}
)
}
```
__[A]{.solved}__: `catch_cnd()` is a simple wrapper around `tryCatch`. If a condition is signalled, it's caught and returned. If no condition is signalled, execution proceeds sequentially and the function returns `NULL`.
The current version of `catch_cnd()` is a little more complex because it allows you to specify which classes of condition you want to capture. This requires some manual code generation because the interface of `tryCatch()` provides condition classes as argument names.
```{r}
rlang::catch_cnd
```
5. __[Q]{.Q}__: How could you rewrite `show_condition()` to use a single handler?
__[A]{.solved}__: Let's use the `condition` argument of `tryCatch` as shown in `rlang::catch_cond()` above:
```{r}
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
}
)
}
# Test
show_condition2(stop("!"))
show_condition2(10)
show_condition2(warning("?!"))
show_condition2({
10
message("?")
warning("?!")
})
```
<!-- ideally explain a bit more what is happening here -->
## Custom conditions
1. __[Q]{.Q}__: 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.
__[A]{.solved}__:
```{r, error = TRUE}
library(rlang)
check_installed <- function(package) {
if (!requireNamespace(package, quietly = FALSE)) {
abort(
"error_pkg_not_found",
message = paste0("package '", package, "' not installed."),
package = package
)
}
TRUE
}
check_installed("ggplot2")
check_installed("ggplot3")
```
2. __[Q]{.Q}__: 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?
__[A]{.solved}__: Instead returning an error it might be preferable to throw a customized condition and place a standardized error message inside the metadata. Then the downstream package could check for the class of the condition, rather than inspecting the message.
## Applications
1. __[Q]{.Q}__: Create `suppressConditions()` that works like `suppressMessages()` and `supressWarnings()` but suppresses everything. Think carefully about how you should handle errors.
__[A]{.solved}__: In general we would like to catch errors, since they contain important information for debugging. In order to suppress the error message and hide the returned error object from the console, we handle errors within a `tryCatch()` and return the error object invisibly:
```{r}
suppressErrors <- function(expr) {
tryCatch(
error = function(cnd) invisible(cnd),
interrupt = function(cnd) stop("Terminated by the user", call. = FALSE),
expr
)
}
```
After we defined the error handling, we can just combine it with the other handlers to create `suppressConditions()`:
```{r}
suppressConditions <- function(expr) {
suppressErrors(suppressWarnings(suppressMessages(expr)))
}
```
To test the new function we apply it to a set of conditions and inspect the returned error object.
```{r}
error_obj <- suppressConditions({
message("message")
warning("warning")
abort("error")
}) # the messages/ wrarnings/ conditions are suppressed successfully
error_obj
```
2. __[Q]{.Q}__: Compare the following two implementations of `message2error()`. What is the main advantage of `withCallingHandlers()` in this scenario? (Hint: look carefully at the traceback.)
```{r}
message2error <- function(code) {
withCallingHandlers(code, message = function(e) stop(e))
}
message2error <- function(code) {
tryCatch(code, message = function(e) stop(e))
}
```
__[A]{.solved}__: Calling handlers are called in the context of the call that signalled the condition. Exiting handlers are called in the context of the call to `tryCatch()`.
```{r, 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
#> })
```
As seen above, the use of `withCallingHandlers()` returns more information and points us to the exact call in our code:
```{r, error = TRUE, eval=FALSE}
message2error2 <- function(code) {
tryCatch(code, message = function(e) (stop("error")))
}
message2error2({1; message("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
#> })
```
3. __[Q]{.Q}__: How would you modify the `catch_cnds()` defined if you wanted to recreate the original intermingling of warnings and messages?
__[A]{.solved}__: To preserve the original order, we have to capture everything into a single list. This makes using this function slightly harder since the caller is responsible for handling the different condition classes.
```{r}
catch_cnds <- function(expr) {
conds <- list()
add_cond <- function(cnd) {
conds <<- append(conds, list(cnd))
cnd_muffle(cnd)
}
tryCatch(
error = function(cnd) {
conds <<- append(conds, list(cnd))
},
withCallingHandlers(
message = add_cond,
warning = add_cond,
expr
)
)
conds
}
# Test
catch_cnds({
inform("message a")
warn("warning b")
inform("message c")
})
```
4. __[Q]{.Q}__: Why is catching interrupts dangerous? Run this code to find out.
```{r, 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.")
}
```
__[A]{.solved}__: When running the `bottles_of_beer()` function in your console, the output should look somehow similar to the following:
```{r, 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.
#>
```
At this point you'll probably recognise how hard it is to get the number of bottles down from `99` to `0`. There's no way to break out of the function because we're capturing the interrupt that you'd usually use!