R 管道工在响应有效负载中从 env 返回错误和对象



我目前正在使用管道工在R中构建API服务。我想知道我的应用程序中的某个函数是否出错,有没有办法尝试捕捉它,这样我就可以同时返回错误本身和错误时环境中存在的对象?任何帮助将不胜感激。

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

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

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

最新更新