【问题标题】:R plumber return error and object from env in response payloadR管道工在响应有效负载中从env返回错误和对象
【发布时间】:2020-09-27 20:36:51
【问题描述】:

我目前正在使用管道工在 R 中构建 API 服务。我想知道我的应用程序中的一个函数是否出错,有没有办法 tryCatch 它以这样一种方式我可以返回错误本身和错误发生时环境中存在的对象?非常感谢任何帮助。

【问题讨论】:

    标签: r try-catch plumber


    【解决方案1】:

    简短的回答是,提供相同的示例,以便可以围绕它构建一些东西。

    更长的答案:这是默认的错误处理程序

    defaultErrorHandler <- function(){
      function(req, res, err){
        print(err)
    
        li <- list()
    
        if (res$status == 200L){
          # The default is a 200. If that's still set, then we should probably override with a 500.
          # It's possible, however, than a handler set a 40x and then wants to use this function to
          # render an error, though.
          res$status <- 500
          li$error <- "500 - Internal server error"
        } else {
          li$error <- "Internal error"
        }
    
    
        # Don't overly leak data unless they opt-in
        if (getOption("plumber.debug", FALSE)) {
          li["message"] <- as.character(err)
        }
    
        li
      }
    }
    

    正如您所见,您可以使用plumber.debug 选项返回有关错误的更多信息。您还可以提供自己的错误处理程序。

    pr <- plumb("plumber.R")
    yourErrorHandler <- function(){
      function(req, res, err, ...){
        #do stuff, set res status you want
      }
    }
    pr$setErrorHandler(fun = yourErrorHandler)
    

    目前似乎缺少此主题的文档。 https://www.rplumber.io/docs/rendering-and-output.html#error-handling

    【讨论】:

      猜你喜欢
      • 2018-08-07
      • 2019-10-23
      • 2020-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-27
      • 2020-08-08
      相关资源
      最近更新 更多