79427680

Date: 2025-02-10 16:24:07
Score: 0.5
Natty:
Report link

@AllanCamerons answer already answers my question in a very elegant way. However, there's one problem that kept bugging me: The function signals both a message and an error. After studying the source code of rlang::signal_abort(), I found that a mix of signalCondition() and cat() mostly mirrors the behavior of rlang::abort():

abort <- function(msg, call = sys.call(1)) {
  cnd <- errorCondition(msg, call = call)
  signalCondition(cnd)
  msg <- sprintf("Error in %s:\n- %s", deparse(call), msg)
  cat(msg, "\n", file = stderr())
  old_options <- options(show.error.messages = FALSE)
  on.exit(options(old_options))
  stop("")
}

What (I think) this does:

Why this is useful:

> tryCatch(abort("something went wrong"), message = \(e) "message caught!")
# Error in tryCatch(abort("something went wrong"), message = function(e) "message caught!"):
# - something went wrong
> tryCatch(abort("something went wrong"), error = \(e) "error caught!")
# [1] "error caught!"
> try(abort("something went wrong"))
# Error : something went wrong
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @AllanCamerons
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: jslth