How to retrieve error message from failing {dplyr} command?

With base R code, we can be fairly certain that when we try-catch a command, if it fails then we'll have access to the message. For example:

> tryCatch(mtcars["test"],  error = function(e) e$message)
[1] "undefined columns selected"

I just tried this with the equivalent dplyr function, and I was surprised to find out that the error thrown by dplyr doesn't contain a message.

> tryCatch(dplyr::select(mtcars, "test"),  error = function(e) e$message)
[1] ""

The dplyr error, when not inside a try-catch, does write the error to the console, but that's not what I want. Does anyone know how to retrieve the message, and also why RStudio chose to do it this way?

Jim Hester and Kevin Ushey both let me know that I can use conditionMessage() for this. So instead of using e$message, it would be conditionMessage(e)

That results in the following:

> tryCatch(dplyr::select(mtcars, "test"),  error = function(e) conditionMessage(e))
[1] "Can't subset columns that don't exist.\n\033[31mx\033[39m Column `test` doesn't exist."

This is correct, but not very user-friendly because of the visual characters that we don't want to keep. Gábor Csárdi gave the tip of using cli::ansi_strip() to remove those:

> tryCatch(dplyr::select(mtcars, "test"),  error = function(e) cli::ansi_strip(conditionMessage(e)))
[1] "Can't subset columns that don't exist.\nx Column `test` doesn't exist."

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.