R-`try`与捕获所有控制台输出结合使用?

R-`try`与捕获所有控制台输出结合使用?,r,error-handling,R,Error Handling,下面是我正在使用的一段代码: install.package('BiocManager');BiocManager::install('UniProt.ws') requireNamespace('UniProt.ws') uniprot_object <- UniProt.ws::UniProt.ws( UniProt.ws::availableUniprotSpecies( pattern = '^Homo sapiens$')$`taxon ID`) query_resu

下面是我正在使用的一段代码:

install.package('BiocManager');BiocManager::install('UniProt.ws')
requireNamespace('UniProt.ws')
uniprot_object <- UniProt.ws::UniProt.ws(
  UniProt.ws::availableUniprotSpecies(
    pattern = '^Homo sapiens$')$`taxon ID`)
query_results <- try(
    UniProt.ws::select(
      x = uniprot_object,
      keys = 'BAA08084.1',
      keytype = 'EMBL/GENBANK/DDBJ',
      columns = c('ENSEMBL','UNIPROTKB')))
install.package('biomanager');BioManager::安装('UniProt.ws')
requireNamespace('UniProt.ws')

uniprot_object正如@Csd所建议的,您可以使用
tryCatch
。您要查找的消息是由R中的
message()
函数打印的,而不是
stop()
,因此
try()
将忽略它。要从
message()
捕获输出,请使用如下代码:

query_results <- tryCatch(
   UniProt.ws::select(
     x = uniprot_object,
     keys = 'BAA08084.1',
     keytype = 'EMBL/GENBANK/DDBJ',
     columns = c('ENSEMBL','UNIPROTKB')), 
   message = function(e) conditionMessage(e))
运行此版本时,
query\u results
保持不变(因为后面的错误中止了执行),但会保存消息:

saveMessages
[1] "Getting mapping data for BAA08084.1 ... and ACC\n"                                                    
[2] "error while trying to retrieve data in chunk 1:\n    no lines available in input\ncontinuing to try\n"

基于@user2554330最优秀的答案,我构建了一个丑陋的东西,它完全符合我的要求:

  • 尝试执行该语句
  • 不要致命地失败
  • 不要留下丑陋的信息
  • 允许我访问
    错误
    s和
    消息
    s
  • 这就是它卑鄙的荣耀:

      saveMessages <- c()
      query_results <- suppressMessages(
        withCallingHandlers(
          try(
            UniProt.ws::select(
              x = uniprot_object,
              keys = 'BAA08084.1',
              keytype = 'EMBL/GENBANK/DDBJ',
              columns = c('ENSEMBL','UNIPROTKB')),
            silent = TRUE),
          message = function(e)
            saveMessages <<- c(saveMessages, conditionMessage(e))))
    

    saveMessages您是否尝试过“tryCatch”功能?通常比“尝试”效果更好。真的很酷-正确的轨道。现在,即使出现错误(如尝试),如何继续?请根据您出色的观察结果,查看下面关于丑陋构造的答案。我不会称之为“丑陋”。您希望对消息和错误执行两种不同的操作:保存前者但继续计算,停止计算但为后者保存消息。因此,您确实需要两个函数:用于错误的
    try()
    tryCatch()
    ,以及用于消息的
    with callinghandlers
    saveMessages
    [1] "Getting mapping data for BAA08084.1 ... and ACC\n"                                                    
    [2] "error while trying to retrieve data in chunk 1:\n    no lines available in input\ncontinuing to try\n"
    
      saveMessages <- c()
      query_results <- suppressMessages(
        withCallingHandlers(
          try(
            UniProt.ws::select(
              x = uniprot_object,
              keys = 'BAA08084.1',
              keytype = 'EMBL/GENBANK/DDBJ',
              columns = c('ENSEMBL','UNIPROTKB')),
            silent = TRUE),
          message = function(e)
            saveMessages <<- c(saveMessages, conditionMessage(e))))