【发布时间】:2021-03-02 03:12:53
【问题描述】:
我想在 R 中创建自己的错误消息以覆盖来自另一个包的错误消息。下面是一个简单的表示:
myfunc <- function(x,y,string=TRUE){
if(string){
x+y
}else{
print("not numeric")
}
}
myfunc(2,"yes")
这会返回:
Error in x + y : non-numeric argument to binary operator
我想用我自己的特定于我的包的错误消息覆盖Error in x + y : non-numeric argument to binary operator,例如Did you forget to use string=TRUE?。我已经在函数中实现了tryCatch 和grepl,它可以工作,但我不确定这是否是最好的方法:
myfunc <- function(x,y,string=TRUE){
tryCatch(myfunc(x,y),
error=function(err){
if (grepl("non-numeric", err$message)) {
stop("Did you forget to use string=TRUE?")
}
})
if(string){
x+y
}else{
print("not numeric")
}
}
myfunc(2,"yes")
这会返回:
Error in value[[3L]](cond) : Did you forget to use string=TRUE?
In addition: There were 50 or more warnings (use warnings() to see the first 50)
Called from: value[[3L]](cond)
这正是我想要的,尽管我更希望它没有说 Error in value[[3L]](cond)。有没有办法摆脱它?另外,这是覆盖错误消息的最佳方法,还是有其他更好的方法?
【问题讨论】:
标签: r error-handling package try-catch grepl