【发布时间】:2017-06-23 13:15:52
【问题描述】:
警告消息在控制台中输出,但如何让这些警告出现在 UI 中,以便用户无需查看控制台即可看到它们?
【问题讨论】:
警告消息在控制台中输出,但如何让这些警告出现在 UI 中,以便用户无需查看控制台即可看到它们?
【问题讨论】:
您可以使用tryCatch 来存储警告对象。
然后,您可以将消息放在 UI 上的任何位置。
library(shiny)
ui <- fluidPage(
actionButton("btn", "click me")
)
server <- function(input, output)
{
observeEvent(input$btn, {
#x <- (1:3 * 1:2) # this generates a warning
#warning("manually generated warning message")
#mess <- names(last.warning)
a <- tryCatch(warning(Sys.time()), warning=function(w) { w })
mess <- a$message
showNotification(mess)
})
}
runApp(list(ui=ui, server=server))
如果操作不繁重,一个简单的方法是运行两次:一次使用tryCatch,另一次不使用。
library(shiny)
ui <- fluidPage(
actionButton("btn", "click me")
)
server <- function(input, output)
{
observeEvent(input$btn, {
x <- tryCatch(1:3 * 1:2, warning=function(w) { w })
if (inherits(x, "simpleWarning")) {
mess <- x$message
showNotification(mess)
x <- 1:3 * 1:2
}
print(x)
})
}
runApp(list(ui=ui, server=server))
如果不希望两次运行相同的操作,则使用以下技巧 (See this SO thread)
library(shiny)
ui <- fluidPage(
actionButton("btn", "click me")
)
server <- function(input, output)
{
withWarnings <- function(expr) {
myWarnings <- NULL
wHandler <- function(w) {
myWarnings <<- c(myWarnings, list(w))
invokeRestart("muffleWarning")
}
val <- withCallingHandlers(expr, warning = wHandler)
list(value = val, warnings = myWarnings)
}
observeEvent(input$btn, {
x <- withWarnings(1:3 * 1:2)
if (!is.null(x$warnings)) {
for (w in x$warnings) showNotification(w$message)
}
})
}
runApp(list(ui=ui, server=server))
【讨论】:
sessionInfo() 的结果。
R version 3.4.0 (2017-04-21) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows >= 8 x64 (build 9200) Matrix products: default locale: [1] LC_COLLATE=English_United States.1252 [2] LC_CTYPE=English_United States.1252 [3] LC_MONETARY=English_United States.1252 [4] LC_NUMERIC=C [5] LC_TIME=English_United States.1252 attached base packages: [1] stats graphics grDevices utils datasets methods base loaded via a namespace (and not attached): [1] compiler_3.4.0 tools_3.4.0