You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R的purrr map中使用tryCatch添加两条错误消息时崩溃

R中purrr::map结合tryCatch的异常处理问题

现象详情

  1. 可正常运行的代码
    将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)
      })
    })
  1. 添加第二条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)
  1. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 12:35:22