R Shiny:强制Shiny抛出错误,而不是为不存在的输入/输出名称静默失败



标题已经说明了一切。我正在维护一个非常大的应用程序,我经常忘记我给事物分配了什么名称。如果我输入了错误的名称,Shiny就会默默地什么也不做,这有时更容易或更困难地被发现。是否有一种方法可以使$操作符正常工作,除了它的第二个参数不存在的情况下,并抛出一个错误?

我尝试在输入上使用get操作符,但无论我是否使item参数为字符串,它都普遍失败。我还尝试了以下操作:它像我期望的那样出错,但对于确实存在的每个元素返回NULL。

`$` = function(obj, item)
{
if (is.list(obj) || is.reactivevalues(obj))
{
item = deparse(substitute(item))
if (!(item %in% names(obj)))
stop(sprintf("%s has no member "%s"", deparse(obj), item))
return(base::`$`(obj, item))
}
else
{
return(base::`$`(obj, item))
}
}

reactivevalues中的$定义在S3类中。你不能仅仅定义"正常"函数。正确的方法如下:

library(shiny)
`$.reactivevalues` <- function(x, name) {
if (!shiny:::hasCurrentContext()) {
rlang::abort(c(
paste0("Can't access reactive value '", name, "' outside of reactive consumer."),
i = "Do you need to wrap inside reactive() or observe()?"
))
}

get_value <- .subset2(x, 'impl')$get(.subset2(x, 'ns')(name))
if(is.null(get_value)) 
stop(sprintf("Current reactiveValues "%s" has no member "%s"", gsub("\(\)", "", deparse(match.call()[2])), name))
get_value
}

deparse(obj)也不是获得当前对象的正确方式,我已经在上面的代码中为您修复了。

我们可以做一些测试

reactiveConsole(TRUE)
abc <- reactiveValues()
abc$a <- 123
abc$a 
# [1] 123
abc$b
# Error in `$.reactivevalues`(abc, b) : 
#  Current reactiveValues "abc" has no member "b"

最新更新