当一个包含许多多层调用的长而复杂的函数抛出错误时,如果不查看堆栈跟踪,就很难理解该错误。但是,当闪亮的应用程序调用这样的函数来处理其输入时,堆栈跟踪似乎只显示应用程序中发生的情况,而不显示它调用的函数中发生的情况。这是一个基于 Hadley Wickham 的Mastering Shiny第 6.3.1 节中的代码的表示:
library(shiny)
f <- function(.x){
# A function with many multi-layered calls.
x_new <- as.numeric(.x)
f_result <- g(x_new)
return(f_result)
}
g <- function(.y){
# Represents a few layers of calls between f() and h().
y_new <- min(.y, 1024)
g_result <- h(y_new)
return(g_result)
}
h <- function(.z){
# A call several layers down.
#
if(.z == 3) stop("Value of 3 not allowed")
h_result <- .z * 2
return(h_result)
}
ui <- fluidPage(
selectInput("n", "N", 1:10),
plotOutput("plot")
)
server <- function(input, output, session) {
output$plot <- renderPlot({
n <- f(input$n)
plot(head(cars, n))
})
}
shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)
当用户输入 3 时,控制台将返回以下内容:
Warning: Error in h: Value of 3 not allowed
[No stack trace available]
Run Code Online (Sandbox Code Playgroud)
所以我可以看到错误发生在h()中,但不是g()代表的一系列调用,这让我进入h()。当使用包含命令的文件run.R运行应用程序时
runApp('T://someNetworkDirectory//App-1', launch.browser=TRUE)
Run Code Online (Sandbox Code Playgroud)
App-1包含一个文件app.R,细节有点不同,但结果是相同的;Traceback()仅显示应用程序开始运行之前发生的情况。捕获显示应用程序调用的函数如何发生错误的堆栈跟踪的最佳方法是什么?