Groovy 如何为异常消息多行 GString

标签 groovy gstring

不应跨越一定数量的字符/行(例如 80 个字符)的 Groovy 错误消息的标准(或最佳实践)是什么?

考虑以下(工作正常)

throw new IOException("""\
        A Jenkins configuration for the given version control
        system (${vcs.name}) does not exist."""
        .stripIndent()
        .replaceAll('\n', ' '))

这将导致没有缩进字符的单行错误消息(我想要的)。但是有没有其他方法(“Groovy 的做法”)如何实现这一点?如果没有,您如何将这样的方法添加到独立 Groovy 应用程序中的 GString 类(如果发现有关 Bootstrap.groovy 文件的提示,但它似乎与 Grails 相关)?

示例:"""考虑如上所示的多行字符串""".toSingleLine()

最佳答案

您可以使用 String 续行字符然后去除多个空格:

throw new IOException( "A Jenkins configuration for the given version control \
                        system (${vcs.name}) does not exist.".replaceAll( /( )\1+/, '$1' ) )

或者您可以将其包装在一个函数中并将其添加到 String.metaClass 中,因为我相信您看到的答案指向了这一点。

您认为 Bootstrap.groovy 是 Grails 的东西是对的,但是如果您只是在应用程序生命周期的早期设置元类,您应该会得到相同的结果...

String.metaClass.stripRepeatedWhitespace = { delegate.replaceAll( /( )\1+/, '$1' ) }

然而,在说这一切时,我可能只是将信息放在一行上

关于Groovy 如何为异常消息多行 GString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9192622/

相关文章:

java - Gradle 任务在应该并行运行时却没有并行运行

groovy - 原因:无此类属性:类org.gradle.api.plugins.Convention的sourceSets

string - Groovy 字符串评估运行时

groovy - 在 Groovy 中获取其名称的变量值

grails - 使用Groovy初始化JAXBContext时,Grails 3.0.8抛出IllegalAnnotationsException的错误1计数

java - 如何通过JMX获取James Server中注册的用户列表

groovy - Groovy 中 GString 中的 Elvis 运算符

使用 Groovy 进行字符串连接

python - Python 中的 GString

java - Groovy 中的匿名代码块