% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/cnd-abort.R, R/cnd-signal.R
\name{abort}
\alias{abort}
\alias{warn}
\alias{inform}
\alias{signal}
\alias{reset_warning_verbosity}
\alias{reset_message_verbosity}
\title{Signal an error, warning, or message}
\usage{
abort(
  message = NULL,
  class = NULL,
  ...,
  call,
  body = NULL,
  footer = NULL,
  trace = NULL,
  parent = NULL,
  use_cli_format = NULL,
  .inherit = TRUE,
  .internal = FALSE,
  .file = NULL,
  .frame = caller_env(),
  .trace_bottom = NULL,
  .subclass = deprecated()
)

warn(
  message = NULL,
  class = NULL,
  ...,
  body = NULL,
  footer = NULL,
  parent = NULL,
  use_cli_format = NULL,
  .inherit = NULL,
  .frequency = c("always", "regularly", "once"),
  .frequency_id = NULL,
  .subclass = deprecated()
)

inform(
  message = NULL,
  class = NULL,
  ...,
  body = NULL,
  footer = NULL,
  parent = NULL,
  use_cli_format = NULL,
  .inherit = NULL,
  .file = NULL,
  .frequency = c("always", "regularly", "once"),
  .frequency_id = NULL,
  .subclass = deprecated()
)

signal(message = "", class, ..., .subclass = deprecated())

reset_warning_verbosity(id)

reset_message_verbosity(id)
}
\arguments{
\item{message}{The message to display, formatted as a \strong{bulleted
list}. The first element is displayed as an \emph{alert} bullet
prefixed with \code{!} by default. Elements named \code{"*"}, \code{"i"}, \code{"v"},
\code{"x"}, and \code{"!"} are formatted as regular, info, success,
failure, and error bullets respectively. See \ifelse{html}{\link[=topic-condition-formatting]{Formatting messages with cli}}{\link[=topic-condition-formatting]{Formatting messages with cli}}
for more about bulleted messaging.

If a message is not supplied, it is expected that the message is
generated \strong{lazily} through \code{\link[=cnd_header]{cnd_header()}} and \code{\link[=cnd_body]{cnd_body()}}
methods. In that case, \code{class} must be supplied. Only \code{inform()}
allows empty messages as it is occasionally useful to build user
output incrementally.

If a function, it is stored in the \code{header} field of the error
condition. This acts as a \code{\link[=cnd_header]{cnd_header()}} method that is invoked
lazily when the error message is displayed.}

\item{class}{Subclass of the condition.}

\item{...}{Additional data to be stored in the condition object.
If you supply condition fields, you should usually provide a
\code{class} argument. You may consider prefixing condition fields
with the name of your package or organisation to prevent name
collisions.}

\item{call}{The execution environment of a currently running
function, e.g. \code{call = caller_env()}. The corresponding function
call is retrieved and mentioned in error messages as the source
of the error.

You only need to supply \code{call} when throwing a condition from a
helper function which wouldn't be relevant to mention in the
message.

Can also be \code{NULL} or a \link[=topic-defuse]{defused function call} to
respectively not display any call or hard-code a code to display.

For more information about error calls, see \ifelse{html}{\link[=topic-error-call]{Including function calls in error messages}}{\link[=topic-error-call]{Including function calls in error messages}}.}

\item{body, footer}{Additional bullets.}

\item{trace}{A \code{trace} object created by \code{\link[=trace_back]{trace_back()}}.}

\item{parent}{Supply \code{parent} when you rethrow an error from a
condition handler (e.g. with \code{\link[=try_fetch]{try_fetch()}}).
\itemize{
\item If \code{parent} is a condition object, a \emph{chained error} is
created, which is useful when you want to enhance an error with
more details, while still retaining the original information.
\item If \code{parent} is \code{NA}, it indicates an unchained rethrow, which
is useful when you want to take ownership over an error and
rethrow it with a custom message that better fits the
surrounding context.

Technically, supplying \code{NA} lets \code{abort()} know it is called
from a condition handler. This helps it create simpler
backtraces where the condition handling context is hidden by
default.
}

For more information about error calls, see \ifelse{html}{\link[=topic-error-chaining]{Including contextual information with error chains}}{\link[=topic-error-chaining]{Including contextual information with error chains}}.}

\item{use_cli_format}{Whether to format \code{message} lazily using
\href{https://cli.r-lib.org/}{cli} if available. This results in
prettier and more accurate formatting of messages. See
\code{\link[=local_use_cli]{local_use_cli()}} to set this condition field by default in your
package namespace.

If set to \code{TRUE}, \code{message} should be a character vector of
individual and unformatted lines. Any newline character \code{"\\\\n"}
already present in \code{message} is reformatted by cli's paragraph
formatter. See \ifelse{html}{\link[=topic-condition-formatting]{Formatting messages with cli}}{\link[=topic-condition-formatting]{Formatting messages with cli}}.}

\item{.inherit}{Whether the condition inherits from \code{parent}
according to \code{\link[=cnd_inherits]{cnd_inherits()}} and \code{\link[=try_fetch]{try_fetch()}}. By default,
parent conditions of higher severity are not inherited. For
instance an error chained to a warning is not inherited to avoid
unexpectedly catching an error downgraded to a warning.}

\item{.internal}{If \code{TRUE}, a footer bullet is added to \code{message}
to let the user know that the error is internal and that they
should report it to the package authors. This argument is
incompatible with \code{footer}.}

\item{.file}{A connection or a string specifying where to print the
message. The default depends on the context, see the \code{stdout} vs
\code{stderr} section.}

\item{.frame}{The throwing context. Used as default for
\code{.trace_bottom}, and to determine the internal package to mention
in internal errors when \code{.internal} is \code{TRUE}.}

\item{.trace_bottom}{Used in the display of simplified backtraces
as the last relevant call frame to show. This way, the irrelevant
parts of backtraces corresponding to condition handling
(\code{\link[=tryCatch]{tryCatch()}}, \code{\link[=try_fetch]{try_fetch()}}, \code{abort()}, etc.) are hidden by
default. Defaults to \code{call} if it is an environment, or \code{.frame}
otherwise. Without effect if \code{trace} is supplied.}

\item{.subclass}{\ifelse{html}{\href{https://lifecycle.r-lib.org/articles/stages.html#deprecated}{\figure{lifecycle-deprecated.svg}{options: alt='[Deprecated]'}}}{\strong{[Deprecated]}} This argument
was renamed to \code{class} in rlang 0.4.2 for consistency with our
conventions for class constructors documented in
\url{https://adv-r.hadley.nz/s3.html#s3-subclassing}.}

\item{.frequency}{How frequently should the warning or message be
displayed? By default (\code{"always"}) it is displayed at each
time. If \code{"regularly"}, it is displayed once every 8 hours. If
\code{"once"}, it is displayed once per session.}

\item{.frequency_id}{A unique identifier for the warning or
message. This is used when \code{.frequency} is supplied to recognise
recurring conditions. This argument must be supplied if
\code{.frequency} is not set to \code{"always"}.}

\item{id}{The identifying string of the condition that was supplied
as \code{.frequency_id} to \code{warn()} or \code{inform()}.}
}
\description{
These functions are equivalent to base functions \code{\link[base:stop]{base::stop()}},
\code{\link[base:warning]{base::warning()}}, and \code{\link[base:message]{base::message()}}. They signal a condition
(an error, warning, or message respectively) and make it easy to
supply condition metadata:
\itemize{
\item Supply \code{class} to create a classed condition that can be caught
or handled selectively, allowing for finer-grained error
handling.
\item Supply metadata with named \code{...} arguments. This data is stored
in the condition object and can be examined by handlers.
\item Supply \code{call} to inform users about which function the error
occurred in.
\item Supply another condition as \code{parent} to create a \link[=topic-error-chaining]{chained condition}.
}

Certain components of condition messages are formatted with unicode
symbols and terminal colours by default. These aspects can be
customised, see \ifelse{html}{\link[=topic-condition-customisation]{Customising condition messages}}{\link[=topic-condition-customisation]{Customising condition messages}}.
}
\details{
\itemize{
\item \code{abort()} throws subclassed errors, see
\code{\link[=rlang_error]{"rlang_error"}}.
\item \code{warn()} temporarily set the \code{warning.length} global option to
the maximum value (8170), unless that option has been changed
from the default value. The default limit (1000 characters) is
especially easy to hit when the message contains a lot of ANSI
escapes, as created by the crayon or cli packages
}
}
\section{Error prefix}{

As with \code{\link[base:stop]{base::stop()}}, errors thrown with \code{abort()} are prefixed
with \code{"Error: "}. Calls and source references are included in the
prefix, e.g. \verb{"Error in }my_function()\verb{ at myfile.R:1:2:"}. There
are a few cosmetic differences:
\itemize{
\item The call is stripped from its arguments to keep it simple. It is
then formatted using the \href{https://cli.r-lib.org/}{cli package} if
available.
\item A line break between the prefix and the message when the former
is too long. When a source location is included, a line break is
always inserted.
}

If your throwing code is highly structured, you may have to
explicitly inform \code{abort()} about the relevant user-facing call to
include in the prefix. Internal helpers are rarely relevant to end
users. See the \code{call} argument of \code{abort()}.
}

\section{Backtrace}{

\code{abort()} saves a backtrace in the \code{trace} component of the error
condition. You can print a simplified backtrace of the last error
by calling \code{\link[=last_error]{last_error()}} and a full backtrace with
\code{summary(last_error())}. Learn how to control what is displayed
when an error is thrown with \code{\link{rlang_backtrace_on_error}}.
}

\section{Muffling and silencing conditions}{

Signalling a condition with \code{inform()} or \code{warn()} displays a
message in the console. These messages can be muffled as usual with
\code{\link[base:message]{base::suppressMessages()}} or \code{\link[base:warning]{base::suppressWarnings()}}.

\code{inform()} and \code{warn()} messages can also be silenced with the
global options \code{rlib_message_verbosity} and
\code{rlib_warning_verbosity}. These options take the values:
\itemize{
\item \code{"default"}: Verbose unless the \code{.frequency} argument is supplied.
\item \code{"verbose"}: Always verbose.
\item \code{"quiet"}: Always quiet.
}

When set to quiet, the message is not displayed and the condition
is not signalled.
}

\section{\code{stdout} and \code{stderr}}{

By default, \code{abort()} and \code{inform()} print to standard output in
interactive sessions. This allows rlang to be in control of the
appearance of messages in IDEs like RStudio.

There are two situations where messages are streamed to \code{stderr}:
\itemize{
\item In non-interactive sessions, messages are streamed to standard
error so that R scripts can easily filter them out from normal
output by redirecting \code{stderr}.
\item If a sink is active (either on output or on messages) messages
are always streamed to \code{stderr}.
}

These exceptions ensure consistency of behaviour in interactive and
non-interactive sessions, and when sinks are active.
}

\examples{
# These examples are guarded to avoid throwing errors
if (FALSE) {

# Signal an error with a message just like stop():
abort("The error message.")


# Unhandled errors are saved automatically by `abort()` and can be
# retrieved with `last_error()`. The error prints with a simplified
# backtrace:
f <- function() try(g())
g <- function() evalq(h())
h <- function() abort("Tilt.")
last_error()

# Use `summary()` to print the full backtrace and the condition fields:
summary(last_error())


# Give a class to the error:
abort("The error message", "mypkg_bad_error")

# This allows callers to handle the error selectively
tryCatch(
  mypkg_function(),
  mypkg_bad_error = function(err) {
    warn(conditionMessage(err)) # Demote the error to a warning
    NA                          # Return an alternative value
  }
)

# You can also specify metadata that will be stored in the condition:
abort("The error message.", "mypkg_bad_error", data = 1:10)

# This data can then be consulted by user handlers:
tryCatch(
  mypkg_function(),
  mypkg_bad_error = function(err) {
    # Compute an alternative return value with the data:
    recover_error(err$data)
  }
)


# If you call low-level APIs it may be a good idea to create a
# chained error with the low-level error wrapped in a more
# user-friendly error. Use `try_fetch()` to fetch errors of a given
# class and rethrow them with the `parent` argument of `abort()`:
file <- "http://foo.bar/baz"
try(
  try_fetch(
    download(file),
    error = function(err) {
      msg <- sprintf("Can't download `\%s`", file)
      abort(msg, parent = err)
  })
)

# You can also hard-code the call when it's not easy to
# forward it from the caller
 f <- function() {
  abort("my message", call = call("my_function"))
}
g <- function() {
  f()
}
# Shows that the error occurred in `my_function()`
try(g())

}
}
\seealso{
\itemize{
\item \ifelse{html}{\link[=topic-error-call]{Including function calls in error messages}}{\link[=topic-error-call]{Including function calls in error messages}}
\item \ifelse{html}{\link[=topic-error-chaining]{Including contextual information with error chains}}{\link[=topic-error-chaining]{Including contextual information with error chains}}
}
}
