The geterrmessage()
function returns the last error message. If you do not want anything very structured or efficient, it is possible to do a quick trick that will accumulate all the error messages in a vector.
Set as an option when you have an error:
options(error= expression(ifelse(exists("erros"),
erros <<- c(erros, geterrmessage()),
erros <<- geterrmessage())))
Then run your script. For example:
1 + "a"
runif("a")
funcaoquenaoexiste()
At the end you will have a vector named erros
with all messages:
cat(erros)
Error in 1 + "a" : non-numeric argument to binary operator
Error in runif("a") : invalid arguments
Error: could not find function "funcaoquenaoexiste"
Once you've done what you need, turn the errors back to normal with:
options(error= NULL)
Another "gambiarra" option is to use knitr. Write your script with markdown in knitr with the option error=TRUE
and at the end you will have everything saved in an HTML document.
If you want something more structured and personalized, you'll have to start with try
or tryCatch
, as rcoster said. For example, the try
function will save the error message if the expression does not execute correctly:
resultado <- try(runif("a"))
resultado
[1] "Error in runif(\"a\") : invalid arguments\n"
attr(,"class")
[1] "try-error"
attr(,"condition")
<simpleError in runif("a"): invalid arguments>
There are more elaborate things in answers to this SOen question.
Hadley has the evaluate package , which might also be useful for you wants to do:
library(evaluate)
erro <- evaluate('runif("a")')
str(erro)
List of 3
$ :List of 1
..$ src: chr "runif(\"a\")"
..- attr(*, "class")= chr "source"
$ :List of 2
..$ message: chr "NAs introduced by coercion"
..$ call : language runif("a")
..- attr(*, "class")= chr [1:3] "simpleWarning" "warning" "condition"
$ :List of 2
..$ message: chr "invalid arguments"
..$ call : language runif("a")
..- attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
Note that he took both the warning and error messages. The error message is the third element in the list:
erro[[3]]
<simpleError in runif("a"): invalid arguments>
erro[[3]]$message
[1] "invalid arguments"