在R的purrr map中使用tryCatch添加两条错误消息时崩溃
R中purrr::map结合tryCatch的异常处理问题
现象详情
- 可正常运行的代码
将tryCatch逻辑放在purrr::map的匿名函数中,当错误处理仅用一条message语句时,代码可正常执行:
map(c(1,2,3), function(x){ record <- tryCatch({ completed <- read_csv("http://example/com/madeup.csv") return(completed) }, error=function(cond) { message("CAUGHT", cond) return(0) }) })
- 添加第二条message后报错
在错误处理块中新增一条单独的message(cond)语句后,代码触发报错:
map(c(1,2,3), function(x){ record <- tryCatch({ completed <- read_csv("http://example/com/madeup.csv") return(completed) }, error=function(cond) { message("CAUGHT") message(cond) return(0) }) })
报错信息:
CAUGHT Error in `map()`: ℹ In index: 1. Caused by error in `open.connection()`: ! Could not resolve host: example Run `rlang::last_error()` to see where the error occurred. Called from: signal_abort(cnd, .file)
- for循环中相同逻辑正常运行
将完全一致的tryCatch逻辑放入for循环,无论多少条message语句都能正常执行:
for(x in c(1,2,3)){ record <- tryCatch({ completed <- read_csv("http://example/com/madeup.csv") return(completed) }, error=function(cond) { message("CAUGHT") message(cond) return(0) }) }
疑问
我记得之前这种map结合tryCatch的写法是可行的,是不是遗漏了purrr或相关包的版本更新内容?
内容的提问来源于stack exchange,提问作者pluke
相关产品推荐
相关产品推荐

