Cookie
Cookie

Reputation: 12652

How to access only the exception error message in R

I have successfully set up my first exception in R

In my function I have a nice stop("Today the moon is blue. Can't continue.")

And I now call it with

tryCatch( {
  XXX(yyy)
}, error = function(err) {
   system(paste('echo "',err,'" | mail -s "BLUE MOON" "[email protected]"',sep=""))
})

The problem is that the err message isn't Today the moon is blue. Can't continue., but a whole mumble jumble in front of it, something along the lines of Error in XXX(yyy) : Today the moon is blue. Can't continue.

Except that XXX and yyy are rather involved and the output just becomes a mess.

How do I access only the error message I threw, without the stuff in front of it? And how would I find the answer myself?

Thanks

Upvotes: 1

Views: 179

Answers (2)

Roman Luštrik
Roman Luštrik

Reputation: 70623

I would do it like this. Based on this error message, you can catch it later and echo to console.

fun <- function(x) stop("Bad moon is rising.")
my.catch <- tryCatch(fun(x = 5), error = function(e) e)
my.catch
<simpleError in fun(x = 5): Bad moon is rising.>
if(grepl("Bad moon is rising.", my.catch)) system(...)

Upvotes: 0

Robert Krzyzanowski
Robert Krzyzanowski

Reputation: 9344

You can use

 system(paste('echo "',err$message,'" | mail -s "BLUE MOON" "[email protected]"',sep=""))

A condition has a message and an internal call language object (how the error was triggered). To see all of it, try print(str(err)), which would have allowed you to deduce that err$message was correct.

Upvotes: 2

Related Questions