【发布时间】:2022-01-01 20:01:27
【问题描述】:
背景
包可以包含很多功能。其中一些需要信息性错误消息,并且可能需要函数中的一些 cmets 来解释发生了什么/为什么发生。例如,f1 在假设的f1.R 文件中。所有文档和 cmets(错误原因和条件)都集中在一个地方。
f1 <- function(x){
if(!is.character(x)) stop("Only characters suported")
# user input ...
# .... NaN problem in g()
# ....
# ratio of magnitude negative integer i base ^ i is positive
if(x < .Machine$longdouble.min.exp / .Machine$longdouble.min.exp) stop("oof, an error")
log(x)
}
f1(-1)
# >Error in f1(-1) : oof, an error
例如,我创建了一个单独的conds.R,指定了一个函数(以及w 警告、s 建议)等。
e <- function(x){
switch(
as.character(x),
"1" = "Only character supported",
# user input ...
# .... NaN problem in g()
# ....
"2" = "oof, and error") |>
stop()
}
然后在f.R 脚本中,我可以将f2 定义为
f2 <- function(x){
if(!is.character(x)) e(1)
# ratio of magnitude negative integer i base ^ i is positive
if(x < .Machine$longdouble.min.exp / .Machine$longdouble.min.exp) e(2)
log(x)
}
f2(-1)
#> Error in e(2) : oof, and error
确实会引发错误,并且在它之上有一个很好的回溯并在控制台中使用调试选项重新运行。此外,作为包维护者,我更喜欢这个,因为它避免考虑编写简洁的 if 语句 + 1 行错误消息或在 tryCatch 语句中对齐 cmets。
问题
是否有理由(对语法没有意见)避免在包中写 conds.R?
【问题讨论】:
标签: r error-handling package-development