Skip to content

Commit

Permalink
handle errors via options(error) instead of withCallingHandlers() to …
Browse files Browse the repository at this point in the history
…make it possible to call globalCallingHandlers(): yihui/knitr#2324
  • Loading branch information
yihui committed Apr 28, 2024
1 parent f1eb5c5 commit 0e096d9
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 5 deletions.
2 changes: 1 addition & 1 deletion R/knitr.R
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ csv_options = function(x) {
x = one_string(x)
res = handle_error(
eval(parse_only(paste('alist(', quote_label(x), ')'))),
function(e, loc) {
function(loc) {
if (loc != '') loc = paste(' at lines', loc)
c(
sprintf('Invalid syntax for chunk options%s:\n', loc), x,
Expand Down
8 changes: 6 additions & 2 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -343,10 +343,14 @@ func_name = function(which = 1) {
handle_error = function(
expr, handler, label = '', fun = getOption('xfun.handle_error.loc_fun')
) {
withCallingHandlers(expr, error = function(e) {
opts = options(error = function() {
loc = if (is.function(fun)) trimws(fun(label)) else ''
message(one_string(handler(e, loc)))
# TODO: remove this workaround after knitr 1.47
m = if (length(formals(handler)) == 1) handler(loc) else handler(list(message = ''), loc)
message(one_string(m))
})
on.exit(options(opts))
expr
}

# a shorthand for rm(list =, envir =)
Expand Down
4 changes: 2 additions & 2 deletions R/yaml.R
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ yaml_load = function(
) {
if (use_yaml) return(handle_error(
yaml::yaml.load(x, eval.expr = FALSE, handlers = yaml_handlers(handlers, envir), ...),
function(e, loc) {
s = e$message
function(loc) {
s = geterrmessage()
r = 'line (\\d+), column (\\d+)'
m = regmatches(s, regexec(r, s, perl = TRUE))[[1]]
if (length(m) < 3) return()
Expand Down

0 comments on commit 0e096d9

Please sign in to comment.