1 year ago
#387276
deschen
How to glue together default error message with custom error message
I'm writing my own package and check some of the inputs. When the inputs aren't in the required format I want to stop with an error. However, I want to add a custom message to the default error.
However, something like this has the problem that the indentation of the default and cutom error message doesn't look nice depending on the input. E.g. could be that the second line is indented by a few chars.
test <- function(x, y, z)
{
if (x != 1)
stop(paste0("oops!", "\n", "x is not 1!"))
}
test(x= 2, y = "this is just a test", z = "we need to make the line very long")
leads to:
Error in test(x = 2, y = "this is just a test", z = "we need to make the line very long") :
oops!
x is not 1!
See how the second line is indented by two characters.
So I thought I write a function this way:
create_stops <- function(error_location, error_message)
{
stop(error_location, "\n", error_message, call. = FALSE)
}
test <- function(x, y, z)
{
if (x != 1)
{
error_location <- match.call()
error_message <- paste0("oops!", "\n", "x is not 1!")
create_stops(error_location, error_message)
}
}
test(x= 2, y = "this is just a test", z = "we need to make the line very long")
which returns:
Error: test2this is just a testwe need to make the line very long
oops!
x is not 1!
So here the problem is that the match.call()
part doesn't return the full message compared to using teh "normal" stop function.
Any idea how I can get the full function call?
Bonus: is there any way how I can prevent having to use the error_location = match.call()
in my main test
function and instead use match.call
in the create_stops
function, but it would return the parent function, i.e. "Error in test", not "Error in create_stops"?
r
error-handling
0 Answers
Your Answer