Ana*_*eam 0 error-handling r try-catch
我试图返回 R 函数中的任何实际错误消息,并向其发送电子邮件以通知用户,但它仅打印 R 参数中的自定义消息。有什么办法可以在电子邮件中发送实际的错误消息吗?
以下是我迄今为止编写的虚拟脚本:
mailme <- function(message){
#function to send email
}
b<-function(){
r <- NULL
attempt <- 1
while( is.null(r) && attempt <= 3 ) {
attempt <- attempt + 1
try({
x<-2+3
prin(x)})
}
stop("The error message")
}
a <- tryCatch({
b()
}, error = function(e){
mailme(e$message)
})
Run Code Online (Sandbox Code Playgroud)
实际返回的错误信息是
Error in prin(x) : could not find function "prin"
Run Code Online (Sandbox Code Playgroud)
但是我在电子邮件中收到的错误消息是
The error message #from the stop used in function b
Run Code Online (Sandbox Code Playgroud)
如何在停靠点内调用实际的错误消息?
我可能误解了你的问题,但我觉得你用两个tryCatches 让事情变得不必要地复杂化。为什么不直接定义您的函数,然后从单个tryCatch. 一个更简化的例子:
# function that will always error
my_fun <- function() prin(x)
tryCatch({
my_fun()
}, error = function(e) {
print(e$message) # replace with mailme(e$message)
})
# [1] "could not find function \"prin\""
Run Code Online (Sandbox Code Playgroud)
当然,在您的实际代码中替换print为。mailme