使用“tryCatch”进行错误处理时,用户在 RStudio 中按“STOP”会发生冲突

Error handling with 'tryCatch' clashes with user pressing 'STOP' in RStudio

提问人:EmilA 提问时间:9/19/2023 更新时间:9/19/2023 访问量:12

问:

我正在从事一个网络抓取项目,我制作了一个函数来处理使用.我的问题是错误处理将我在 RStudio 中按下“STOP”按钮视为错误,并通过等待来处理此错误。我希望被允许停止执行该函数。GET

函数如下:

# Handle read_html errors
get_page <- function(url, user_agent = "[my information]", skipped) {
  headers <- add_headers(`User-Agent` = user_agent)
  
  if (!exists(skipped, envir = .GlobalEnv)) {
    assign(skipped, c(), envir = .GlobalEnv)
  }
  
  for (attempt in 1:4) {
    start_time <<- Sys.time()
    tryCatch({
      response <- GET(url, headers = headers)
      http_code <- response$status_code
      
      if (http_code == 200) {
        page <- read_html(rawToChar(response$content))
        return(page)
        
      } else if (http_code %in% c(400, 401, 403, 404)) {
        cat("HTTP", http_code, "error for", url, "\n")
        assign(skipped, c(get(skipped), url), envir = .GlobalEnv)
        return(NULL)
      }

    }, error = function(e) {
      cat("Error:", conditionMessage(e), "\n")
      Sys.sleep(60)  # Wait before retrying
      
      if (attempt == 4) {
        cat("Skipped", url, "\n")
        assign(skipped, c(get(skipped), url), envir = .GlobalEnv)
        return(NULL)
      }
    })
  }
}

当我按“停止”时,控制台会打印此消息,然后等待 60 秒并重试。我只能通过强制终止 RStudio 来使函数停止。Error: Operation was aborted by an application callback

我试过让该函数允许我通过添加以下内容来停止它:

# ... first part of my code

    return(NULL)
  }

  }, error = function(e) {
      if (inherits(e, "interrupt")) {
        cat("Execution interrupted by user.\n")
        return(NULL) 
      } else {
        cat("Error:", conditionMessage(e), "\n")
        Sys.sleep(60)  

# ... rest of the code

...和:

# ... first part of my code

  }, interrupts = function(e) {
      cat("Interrupted by the user\n")
      return(NULL)
    }, error = function(e) {
      cat("Error:", conditionMessage(e), "\n")
      Sys.sleep(60)  # Wait before retrying

# ... rest of my code

但是当我抓取并预处理“STOP”时,例如在这个循环中,它的作用与以前完全相同(打印消息,然后等待 60 秒并重试)Error: Operation was aborted by an application callback

for (i in 0:143) {
  progress(i, 0:143)
  url <- paste0(base, i)
  page <- get_page(url, skipped = "skip_excel_au")
  
  url_pers <- c(url_pers,
                page %>% html_nodes("a.link.person") %>% html_attr("href") 
  )
  Sys.sleep(1)
  
}
r 错误处理 try-catch

评论


答: 暂无答案