3

What is the standard (or best practice) for Groovy error messages that that shouldn't span over a certain number of characters/line, e.g., 80 characters?

Consider the following (which is working fine)

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

This will result in a one-line error message with no indention characters (what I want). But is there some other way ("the Groovy way of doing it") how to achieve this? If not, how could you add such a method to the GString class in a standalone Groovy application (if found hints regarding a Bootstrap.groovy file but it seems to be related to Grails)?

Example: """Consider a multi line string as shown above""".toSingleLine()

TommyMason
  • 495
  • 4
  • 13

1 Answers1

3

You could use the String continuation character then strip multiple spaces:

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

Or you could wrap this in a function and add it to the String.metaClass as I believe the answers you've seen point to.

You're right in thinking that Bootstrap.groovy is a Grails thing, but if you just set the metaClass early on in your applications lifecycle, you should get the same result...

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

In saying all this however, I'd probably just keep the message on a single line

tim_yates
  • 167,322
  • 27
  • 342
  • 338