使用 knitr 从 R 获取显示的错误消息,因为它们本机出现在 R 会话中

Get error messages from R displayed as they natively appear in an R session using knitr

我想使用 Rmarkdown 构建一个 html 文档,其中可以显示来自 R 的错误消息,因为它们在 R 交互式会话中本机出现。

类似,但不要求错误消息的显示与交互式会话中的完全相同:我尝试对给定的块使用 error=TRUE,错误的前缀为Error in eval(expr, envir, enclos)::

具有以下块:

```{r, error=TRUE}
notexistingvariable
```

我预计:

Error: object 'notexistingvariable' not found

我得到:

Error in eval(expr, envir, enclos): object 'notexistingvariable' not found

我尝试添加 results="asis" 选项,但这在这里没有效果。我认为这只适用于非错误输出。


尝试使用 wrap.error

按照建议 ,我尝试设置自定义 wrap.error 函数。

test.Rmd:

---
title: "test"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

wrap.error <- function(x, options) {
  # x is an error object, with components "call" and "message".  Ignore
  # the call, but wrap the result like code:
  paste0("```\n## Error: ", x$message, "\n```")
}
```

```{r, error=TRUE}
notexistingvariable
```

转换为 html:

$ R -e "rmarkdown::render('test.Rmd',output_file='test.html')"

R version 3.5.1 (2018-07-02) -- "Feather Spray"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> rmarkdown::render('test.Rmd',output_file='test.html')


processing file: test.Rmd
  |................                                                 |  25%
  ordinary text without R code

  |................................                                 |  50%
label: setup (with options) 
List of 1
 $ include: logi FALSE

  |.................................................                |  75%
  ordinary text without R code

  |.................................................................| 100%
label: unnamed-chunk-1 (with options) 
List of 1
 $ error: logi TRUE


output file: test.knit.md

/usr/bin/pandoc +RTS -K512m -RTS test.utf8.md --to html4 --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash --output test.html --smart --email-obfuscation none --self-contained --standalone --section-divs --template /home/bli/R/x86_64-pc-linux-gnu-library/3.5/rmarkdown/rmd/h/default.html --no-highlight --variable highlightjs=1 --variable 'theme:bootstrap' --include-in-header /tmp/RtmpAoBtc7/rmarkdown-str53186fa5c04d.html --mathjax --variable 'mathjax-url:https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML' 

Output created: test.html
> 
> 

test.html 文件如下所示:


使用 wrap.simpleError,正如现在更新的答案所建议的那样,有效。

(已更新以反映 R 3.5.x 更改)

您可以为输出设置自定义渲染器(参见 vignette("knit_print")),但我认为发生错误时不会调用它们。在这种情况下调用通用 wrap() 函数。 knitr 定义了一个 wrap.error() 方法,在 R 3.5.0 之前,它可以被用户覆盖。但是,在最新版本的 R 中,优先选择包中定义的方法而不是用户定义的方法,因此它不再有效。

不过,有些错误还是有解决办法的。对于问题中的示例,创建的错误对象具有 class c("simpleError", "error", "condition"),并且 knitr 未定义 wrap.simpleError() 方法。您可以定义一个,并覆盖其处理。

你这样做:

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

wrap.simpleError <- function(x, options) {
  # x is an error object, with components "call" and "message".  Ignore
  # the call, but wrap the result like code:
  paste0("```\n## Error: ", x$message, "\n```")
}
```

```{r, error=TRUE}
notexistingvariable
```

这会显示如下结果:

还有一个输出挂钩来处理错误:请参阅 https://yihui.name/knitr/hooks/。但是,它似乎是在 wrap.error 之后调用的,当消息已经形成时。您可以编辑该消息以删除 您不想要的部分使用这样的代码:

```{r}   
knitr::knit_hooks$set(error = function(x, options) {
  paste0("```\n", 
         sub(" in eval(expr, envir, enclos)", "", x, fixed = TRUE),
         "\n```")
})
```e

这可能比 wrap.simpleError 方法更可靠,后者 如果 knitr 曾经定义过这样的 wrap.simpleError 方法,它将停止工作。它还将处理所有错误,而不仅仅是 "simpleError" 个错误。它有 缺点是可能更难定制它来处理不同类型的错误,并且可能无法在 "Error in" 被翻译成其他语言的不同语言环境中工作。