gpt4 book ai didi

Groovy 如何为异常消息多行 GString

转载 作者:行者123 更新时间:2023-12-02 00:24:59 25 4
gpt4 key购买 nike

不应跨越一定数量的字符/行(例如 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com