The function geterrmessage()
returns the last error message. If you don’t want anything very structured or efficient, you can do a quick hack that accumulates all the error messages in one vector.
Set as 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 called 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"
After you do what you need, turn the mistakes 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 will have to go to try
or tryCatch
, as rcoster said. For example, the function try
will save the error message if the expression is not executed 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 answer to Soen’s question.
Hadley has the package evaluate, that maybe also serve for what you are wanting 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 it took both the Warning and the error message. The error message is the third element in the list:
erro[[3]]
<simpleError in runif("a"): invalid arguments>
erro[[3]]$message
[1] "invalid arguments"
Take a look at the help from
try
andtryCatch
. I believe they’re meant for what you want. Just be careful that you sent us 2 types of message: one error and another warning (Warning), are different things.– Rcoster
@Rcoster was just like that! you don’t want to put in the answer?
– Daniel Falbel
I did not want to send as an answer because I do not know these functions, I preferred to give the chance to someone explain better than me, so I learn too!
– Rcoster