簡體   English   中英

是否可以覆蓋基本 R 錯誤消息?

[英]Is it possible to overwrite base R error messages?

我想覆蓋來自基本 R 函數的不太有用的錯誤消息,並將其替換為自定義錯誤消息。 我怎么能做到這一點?

為了澄清,假設我評估以下表達式"a" + "b" 因為我試圖添加兩個字符,所以 R 會抱怨並返回““a”+“b”中的錯誤:二進制運算符的非數字參數”。

有沒有辦法捕捉到這個確切的錯誤消息,並返回更清晰的錯誤消息,例如“您正在嘗試添加兩個因素 - 這是不允許的”?

我想一個起點是使用try函數和grepl

a <- try("a" + "a", silent = TRUE)

if(inherits(a, "try-error")){
  cond <- sum(grepl("non-numeric argument to binary operator", deparse(a), fixed = TRUE)) > 0
  if(cond){
    stop("You are trying to add two characters. This is not allowed.")
  }
}

但也許有一種更“通用”或“優雅”的方式來做到這一點?

您可以使用inherits檢查類,然后使用grepl使用"condition"屬性,如下所示,就像您建議的那樣

a <- try("a" + "a", silent = TRUE)
if(inherits(a, "try-error") && grepl("non-numeric argument to binary operator$", attr(a, "condition")$message))
    stop("You are trying to add two non-numbers")
#R> Error: You are trying to add two non-numbers

但似乎很多事情都可能導致這個錯誤。 例如

a <- try(list() + list(), silent = TRUE)
if(inherits(a, "try-error") && grepl("non-numeric argument to binary operator$", attr(a, "condition")$message))
    stop("You are trying to add two non-numbers")
#R> Error: You are trying to add two non-numbers

如果可能的話,一個更好的主意可能是檢查參數。 例如使用stopifnot()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM