Shiny - Error in ..stacktraceon..: could not find function "shioptions" - r

I have never seen this error before running a Shiny app and can't find anything about it after Googling. I've tried re-installing the shiny package and restarting R but nothing resolves it. Any insight?
Error after running runApp() from the local directory:
Listening on http://127.0.0.1:6093
Warning: Error in ..stacktraceon..: could not find function "shioptions"
Stack trace (innermost first):
1: runApp
Error in ..stacktraceon..({ : could not find function "shioptions"
Traceback below:
5: Sys.sleep(0.001)
4: withCallingHandlers(expr, error = function(e) {
if (is.null(attr(e, "stack.trace", exact = TRUE))) {
calls <- sys.calls()
attr(e, "stack.trace") <- calls
stop(e)
}
})
3: captureStackTraces(while (!.globals$stopped) {
serviceApp()
Sys.sleep(0.001)
})
2: ..stacktraceoff..(captureStackTraces(while (!.globals$stopped) {
serviceApp()
Sys.sleep(0.001)
}))
1: runApp()

Check the library("shiny") output from your R Console. I think you do not have the package loaded and/or you had an intentional upgrade.

Related

R: Errorhandling with tryCatchLog - create a customizable result code for the console and write a detailled traceback to log file

I have code that includes several initial checks of different parameter values. The code is part of a larger project involving several R scripts as well as calls from other environments. If a parameter value does not pass one of the checks, I want to
Generate a customizable result code
Skip the remaining code (which is not going to work anyhow if the parameters are wrong)
Create a log entry with the line where the error was thrown (which tells me which test was not passed by the parameters)
Print my customizable result code to the console (without a more detailed explanation / trace back from the error)
Otherwise, the remaining code should be run. If there are other errors (not thrown by me), I also need an error handling resulting in a customizable general result code (signalling that there was an error, but that it was not one thrown by me) and a more detailled log.
The result codes are part of the communication with a larger environment and just distinguishes between wrong parameter values (i.e., errors thrown by me) and other internal problems (that might occur later in the script).
I would like to use tryCatchLog because it allows me to log a detailed traceback including the script name (I am sourcing my own code) and the line number. I have not figured out, however, how to generate my own error code (currently I am doing this via the base function stop()) and pass this along using tryCatchLog (while also writing a log).
Example
In the following example, my parameter_check() throws an error via stop() with my result code "400". Using tryCatchLog I can catch the error and get a detailed error message including a traceback. However, I want to seperate my own error code (just "400"), which should be printed to the console, and a more detailed error message, which should go to a log file.
library(tryCatchLog)
parameter_check <- function(error) {
if (error){
stop("400")
print("This line should not appear")
}
}
print("Beginning")
tryCatchLog(parameter_check(error = TRUE),
error = function(e) {print(e)}
)
print("End")
Currently, the result is:
[1] "Beginn"
ERROR [2021-12-08 11:43:38] 400
Compact call stack:
1 tryCatchLog(parameter_check(0), error = function(e) {
2 #3: stop("400")
Full call stack:
1 tryCatchLog(parameter_check(0), error = function(e) {
print(e)
2 tryCatch(withCallingHandlers(expr, condition =
cond.handler), ..., finall
3 tryCatchList(expr, classes, parentenv, handlers)
4 tryCatchOne(expr, names, parentenv, handlers[[1]])
5 doTryCatch(return(expr), name, parentenv, handler)
6 withCallingHandlers(expr, condition = cond.handler)
7 parameter_check(0)
8 #3: stop("400")
9 .handleSimpleError(function (c)
{
if (inherits(c, "condition")
<simpleError in parameter_check(0): 400>
I would like to get my own result code ("400") so that I can print it to the console while logging the complete error message in a file. Is there a way of doing it without writing code parsing the error message, etc.?
Solution with tryCatch
Based on the hint by R Yoda and this answers this is a solution with tryCatch and calling handlers.
### Parameters
log_file_location <- "./logs/log.txt"
### Defining functions
parameter_check_1 <- function(error) {
if (error){
stop("400")
}
}
parameter_check_2 <- function(error) {
if (error){
stop("400")
}
}
write_to_log <- function(file_location, message) {
if (file.exists(file_location))
{write(message, file_location, append = TRUE)}
else
{write(message, file_location, append = FALSE)}
}
parameter_check <- function(){
print("Beginning of parameter check")
print("First check")
parameter_check_1(error = TRUE)
print("Second check")
parameter_check_2(error = FALSE)
print("End of parameter check")
}
main<- function() {
print("Beginning of main function")
log(-1) # throws warning
log("error") # throws error
print("End of main function")
}
### Setting parameters
result_code_no_error <- "200"
result_code_bad_request <- "400"
result_code_internal_error <- "500"
# initial value for result_code
result_code <- result_code_no_error
print("Beginning of program")
### Execute parameter check with tryCatch and calling handlers
# Error in parameter checking functions should result in result_code_bad_request
tryCatch(withCallingHandlers(parameter_check(),
error = function(condition){},
warning = function(condition){
write_to_log(log_file_location, condition$message)
invokeRestart("muffleWarning")
}
),
error = function(condition) {
write_to_log(log_file_location, condition$message)
result_code <<- result_code_bad_request
}
)
### Execute main section with tryCatch and calling handlers
# Error in main section should result in result_code_internal_error
# main section should only be excecuted if there is no error (internal or bad request) in the previous section
if (result_code == result_code_no_error) {
tryCatch(withCallingHandlers(main(),
error = function(condition){},
warning = function(condition){
write_to_log(log_file_location, condition$message)
invokeRestart("muffleWarning")
}
),
error = function(condition) {
write_to_log(log_file_location, condition$message)
result_code <<- result_code_internal_error
}
)
}
print("End of program")
print(result_code)
As explained in the vignette for tryCatchLog this has the disadvantage of not logging the precise location of the error. I am not passing on the error message from stop("400"), because all parameter checking functions are in one function call now, but this could be done using condition$message.
The solution is (totally independent of using tryCatchLog or standard R tryCatch):
...
error = function(e) {print(e$message)}
..
Background (how R errors work): They create an object of type (error) condition:
e <- simpleError("400") # same "condition" object as created by stop("400")
str(e)
# List of 2
# $ message: chr "400"
# $ call : NULL
# - attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
print(e$message)
[1] "400"

R Shiny - Downloading a PDF Report Error

The issue is weird in the sense that I can recreate the exact same PDF report with knitr outside of the Shiny app. The code does work if I use HTML as output format. I have the latest version from MikTex
See code below:
output$report <- downloadHandler(
filename = paste(Sys.Date(), "GebiedsRapportage.html"),
content = function(file) {
#tempReport <- file.path(tempdir(), "report_html.Rmd")
tempReport <- file.path(tempdir(), "report_pdf.Rmd")
#file.copy("report_html.Rmd", tempReport, overwrite = TRUE)
file.copy("report_pdf.Rmd", tempReport, overwrite = TRUE)
rmarkdown::render(tempReport, output_file = file)
}
)
So, using the #HTML functions works fine, but the PDF function gives me the following error:
Warning: running command '"pdflatex" -halt-on-error -interaction=batchmode "file2e8466131256.tex"' had status 1
Warning: Error in : Failed to compile file2e8466131256.tex.
Stack trace (innermost first):
58: show_latex_error
57: on_error
56: system2_quiet
55: run_engine
54: latexmk_emu
53: tinytex::latexmk
52: latexmk
51: rmarkdown::render
50: download$func [server/server_data_analysis.R#311]
1: runApp
Error : Failed to compile file2e8466131256.tex.
While knitting the file itself without interacting with Shiny generates a PDF perfectly fine.
Anyone encountered the same issue?

R shiny segfaulting

I have just installed shiny 1.0.5 in Ubuntu 14.04.5 LTS and am receiving a segmentation fault on the default landing page. The last bit of the Javascript console/hello error log is:
89: .Call("httpuv_run", PACKAGE = "httpuv", timeoutMillis)
90: run(timeoutMs)
91: service(timeout)
92: serviceApp()
93: withCallingHandlers(expr, error = function(e) { if (is.null(attr(e, "stack.trace", exact = TRUE))) { calls <- sys.calls() attr(e, "stack.trace") <- calls stop(e) }})
94: captureStackTraces({ scheduleFlush() while (!.globals$stopped) { serviceApp() Sys.sleep(0.001) }})
95: ..stacktraceoff..(captureStackTraces({ scheduleFlush() while (!.globals$stopped) { serviceApp() Sys.sleep(0.001) }}))
96: runApp(Sys.getenv("SHINY_APP"), port = port, launch.browser = FALSE)
An irrecoverable exception occurred. R is aborting now ...
-su: line 1: 2739 Segmentation fault (core dumped) R --no-save --slave -f \/opt\/shiny-server\/R\/SockJSAdapter\.R
Also, from the beginning of the log file:
*** caught segfault ***
address 0xbd, cause 'memory not mapped'
Any tips on debugging this and getting it running?
I don't ultimately know what the issue is, but upgrading to R 3.4.2 had completely broken Shiny. Removing r-base (r-base-core, etc) via apt and reinstalling 3.3.3 fixed the issue, though it remains frustrating.

How to access the environment of the function that started a Shiny application?

I have a Shiny application that I run by calling a function that calls shiny::runApp. The application can access the global environment, therefore it can access to data in objects that have a name decided in advance. However, I would like to pass it data through the parameters of the function that runs the app. The following example works.
f <- function(param) {
runApp(
list(
ui = fixedPage({
verbatimTextOutput('text')
}),
server = function(input, output) {
output$text <- renderPrint(param)
})
)
}
f("hello")
However, I can not reproduce this behaviour when the ui and server components are loaded from a file:
File contents:
$ cat ui.R
fixedPage({
verbatimTextOutput('text')
})
$ cat server.R
function(input, output) {
output$text <- renderPrint(param)
}
R code:
g <- function(param) {
runApp()
}
g("hello")
Error message:
Listening on http://127.0.0.1:3870
Warning: Error in renderPrint: object 'param' not found
Stack trace (innermost first):
86: renderPrint
85: func
84: eval
83: eval
82: withVisible
81: evalVis
80: utils::capture.output
79: paste
78: origRenderFunc
77: output$text
2: runApp
1: g [#2]
I guess that it has something to do with the fact that the components are not created in similar scopes in the two examples, but I could not find a workaround... In the second example, is there a way where I can access the environment of the function g from the Shiny app ?
Yes. Define the param object in the global environment:
g <- function(param) {
assign("param",param,.GlobalEnv)
runApp()
}
#this now works and print `hello` as intended
g("hello")

R avoiding "restarting interrupted promise evaluation" warning

Problem
It seems that within a function, when you evaluate an expression that yields an error more than once, you get the warning restarting interrupted promise evaluation. For instance:
foo <- function() stop("Foo error")
bar <- function(x) {
try(x)
x
}
bar(foo())
yields
Error in foo() : Foo error
Error in foo() : Foo error
In addition: Warning message:
In bar(foo()) : restarting interrupted promise evaluation
How to avoid this warning and deal with it properly?
Background
Especially with operations like writing to a database, you might encounter locking errors that require you to retry your operation a few times. Hence I'm creating a wrapper around tryCatch that re-evaluates an expression up to n times until successful:
tryAgain <- function(expr, n = 3) {
success <- T
for (i in 1:n) {
res <- tryCatch(expr,
error = function(e) {
print(sprintf("Log error to file: %s", conditionMessage(e)))
success <<- F
e
}
)
if (success) break
}
res
}
However, I'm getting loads of restarting interrupted promise evaluation messages:
> tryAgain(foo())
[1] "Log error to file: Foo error"
[1] "Log error to file: Foo error"
[1] "Log error to file: Foo error"
<simpleError in foo(): Foo error>
Warning messages:
1: In doTryCatch(return(expr), name, parentenv, handler) :
restarting interrupted promise evaluation
2: In doTryCatch(return(expr), name, parentenv, handler) :
restarting interrupted promise evaluation
Ideally I want to avoid these messages altogether rather than just muffle them, since I might also want to handle genuine warnings coming from expr.
You can also try this without silent=TRUE if you want each error message to show. In neither case will you get the message about promises:
foo <- function() stop("Foo error")
bar <- function(x) {
try(eval.parent(substitute(x)), silent = TRUE)
x
}
bar(foo())

Resources