8.2 Signalling conditions
8.2.1 Types of conditions
Three types of conditions:
- ❌ Errors. Problem arose, and the function cannot continue.
- ⚠️ Warnings. Problem arose, but the function can continue, if only partially.
- 💬 Messages. Something happened, and the user should know.
8.2.2 ❌ Errors
How to throw errors
# with base R
stop("... in the name of love...")
#> Error: ... in the name of love...
# with rlang
rlang::abort("...before you break my heart...")
#> Error:
#> ! ...before you break my heart...
# with base R; without call
stop("... think it o-o-over...", call. = FALSE)
#> Error: ... think it o-o-over...
Composing error messages
- Mechanics.
stop()
pastes together arguments
abort()
requires{glue}
- Style. See here.
8.2.3 ⚠️ Warnings
May have multiple warnings per call
warn <- function() {
warning("This is your first warning")
warning("This is your second warning")
warning("This is your LAST warning")
}
Print all warnings once call is complete.
warn()
#> Warning in warn(): This is your first warning
#> Warning in warn(): This is your second warning
#> Warning in warn(): This is your LAST warning
Like errors, warning()
has
- a call argument
- an
{rlang}
analog
# base R
# ... with call (implicitly .call = TRUE)
warning("Warning")
#> Warning: Warning
# ... with call suppressed
warning("Warning", call. = FALSE)
#> Warning: Warning
# rlang
# note: call suppressed by default
rlang::warn("Warning")
#> Warning: Warning
(Hadley’s) advice on usage:
- Err on the side of errors. In other words, error rather than warn.
- But warnings make sense in a few cases:
- Function is being deprecated. Warn that it is reaching end of life.
- Function is reasonably sure to recover from issue.
8.2.4 💬 Messages
Mechanics:
- Issued immediately
- Do not have a call argument
Style:
Messages are best when they inform about:
- Default arguments
- Status updates of for functions used primarily for side-effects (e.g., interaction with web API, file downloaded, etc.)
- Progress of long-running process (in the absence of a status bar).
- Package loading message (e.g., attaching package, objects masked)