Stopping an R script without getting "Error during wrapup" message - r

I wrote an R script which writes messages (progress report) to a text file. I modified the error option so that when an error occurs, the error message is also written to that file:
options(error = function() {
cat(geterrmessage(),file = normalizePath("logs/messages.txt"),append = TRUE)
stop()
})
It works, but I get this message in the console/terminal window when an error does occur:
Error during wrapup:
Execution halted
So I'm thinking there's a better way to interrupt the execution of the script... or is there?

I just found this inside R source code:
if (inError) {
/* fail-safe handler for recursive errors */
if(inError == 3) {
/* Can REprintf generate an error? If so we should guard for it */
REprintf(_("Error during wrapup: "));
/* this does NOT try to print the call since that could
cause a cascade of error calls */
Rvsnprintf(errbuf, sizeof(errbuf), format, ap);
REprintf("%s\n", errbuf);
}
stop() causes the error handler to be executed. If the stop() call occurs within the error handler, R displays the Error during wrapup: message and prevents you from the infinite recursion that would occur otherwise.
Do not call stop() from inside your options$error.
Use q(save="no", status=1, runLast=FALSE) instead, that should do exactly what the default error handler does for non-interactive use. See ?options for the meaning of options$error and ?stop for details about error handling.

Related

Problem in writing error logs to a file in R

I'd like to do some error handling in my R program. So I'm using tryCatch function and I would like to write the error message (in case there is any error to a file). Here is the code I have
basicConfig(level='INFO')
addHandler(writeToFile, file=file_name.txt, level='INFO')
tryCatch(
{
logger <- getLogger()
...
},
error=function(cond) {
logger$error(cond)
})
but it looks like cond does not contain the error message and the log file ends up as empty. How can I write down th error thread/message then?

How to use option(error = ) with a custom function and still make the script abort (in R)

Can anyone point me to the best way to use option(error = function(...){}) properly? I want to write errors to a log file and then terminate as usually. Currently I use
options(error = function(...) {
#... write to logfile ...
options(error = NULL)
stop(geterrmessage())
})
But resetting the option and calling stop() again looks like a hack to me. I also tried q("no", status = 1, runLast = FALSE) (as from the documentation of stop()), but this does not seem to be equivalent to a normal stop(). For example, in RStudio server it quits the whole session.
I need to use the option() instead of tryCatch() because I want to catch all possible errors that occur in the script. I launch my script via a cron job, and I want to get an email/log entry as soon as the script fails.
A tryCatch block would probably be the best option for this type of situation.
tryCatch({
#... main code to run ...
}, warning = function(w) {
#... code to run if any warnings occur ...
warning(w) # Show the warning
}, error = function(e) {
#... write to log file ...
stop(e) # Stop script and show error message. Delete this line if you do not want to stop script
}, finally = {
#... code to run whether or not error occurs ...
})

MathJax - Math Process Error while adding equation

I'm using wiris editor to insert MathML, the MathML equation is as shown in the attached image.
When the MathML is processed by MathJax, the following error is occuring
When a callback is define at "Math Processing Error"
MathJax.Hub.Register.MessageHook("Math Processing Error",function (message) {
console.log(message[2].stack); // message[2] is the error object
});
It throws an exception saying
TypeError: Cannot read property 'firstChild' of null
at MathJax.Hub.Register.StartupHook.h.mo.Augment.CHTMLstretchV (TeX-AMS-MML_HTMLorMML.js?rev=2.5.3:62)

getForm: retry connection upon error

For a web scraping project I am making frequent requests on a particular site. Sometimes the connection times out with an error and I would like for it to retry instead of erroring out. I've written out the code below for it to keep trying, but I don't think it works because I still error out.
url = "www.google.com"
while(true){
withRestarts(tryCatch(
sourcecode <- getForm(urls[n]),
finally = Sys.sleep(2),
abort = function(){})
}
Error in function (type, msg, asError = TRUE) : couldn't connect to
host
Got it after experimenting:
while(length(sourcecode.ad) == 0){
try({
sourcecode <- getForm(urls[n])
print(urls[n])
Sys.sleep(1)
})
}
Try() will allow a continuation after an error occurs. Combined with the loop, it will keep retrying.

phpunit fail message for wrong exception thrown

I'm using phpunit for TDD approach. Currently, some tests I've already written fail, because I'm waiting for other people to catch up with my tests. Therefore, I want to print out a failed assertion message for each assertion that fails now, e.g.
$this->assertTrue($now_its_false, '> my friend should fix method X to return Y');
This works for standard assertions, but I can't figure out how to print such message when testing exceptions. For example, I've test a method that should raise an exception, but it doesn't. My code looks like this:
public function testSomethingIncorrect() {
$this->setExpectedException('SomeException');
$object->doSomethingThatShouldRaiseException();
$this->fail('This call should raise exception!');
}
How to print out the test fail message here?
There is no "clear" way to achieve this. You can notice that PHPUnit_Framework_Constraint_Exception doesn't take any description argument.
Anyway you can do it "around".
try {
$object->doSomethingThatShouldRaiseException();
$this->fail('This call should raise exception!');
} catch ('SomeException') {
}

Resources