Skip to content

Instantly share code, notes, and snippets.

@klmr
Last active August 30, 2019 02:00
Show Gist options
  • Save klmr/ca110f867c059616ae88d76ceee9d47e to your computer and use it in GitHub Desktop.
Save klmr/ca110f867c059616ae88d76ceee9d47e to your computer and use it in GitHub Desktop.
Simple error handling with subclasses in R. Code is a direct port of Python code from https://codereview.stackexchange.com/q/225419/308
os_error = function (message, call = NULL) {
class = c('os_error', 'error', 'condition')
structure(list(message = message, call = call), class = class)
}
value_error = function (message, call = NULL) {
class = c('value_error', 'error', 'condition')
structure(list(message = message, call = call), class = class)
}
open = function (filename, mode = 'rb') {
tryCatch(
base::file(filename, open = mode),
error = function (.) stop(os_error(glue::glue('Cannot open file {filename}')))
)
}
readline = function (file) {
tryCatch(
readLines(file, n = 1L),
error = function (.) stop(value_error('Error reading from file'))
)
}
int = function (str) {
tryCatch(
as.integer(str),
warning = function (w) stop(value_error(conditionMessage(w)))
)
}
i = tryCatch(
{
f = open('errors.r')
on.exit(close(f))
s = readline(f)
int(s)
},
os_error = function (e) {
# This code could be shortened with an appropriate S3 method.
message(glue::glue('OS error: {conditionMessage(e)}'))
},
value_error = function (e) {
message(glue::glue('Value error: {conditionMessage(e)}'))
},
error = function (e) {
message(glue::glue('Unexpected error: {conditionMessage(e)}'))
stop(e)
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment