Better error handling when a property is not set


(ron.smits) #1

I am playing a bit with Gradle and wanted to have a “profile property” like thingy. I use the following code found on SO:

// define the profileProperties. This is basically the profile and properties like in maven
def profileProperties = [
 dev:[
  dbdriver:"org.apache.derby.jdbc.EmbeddedDriver",
  dburl:"jdbc:derby:db/eveasset;create=true",
  dbuser:"app",
  dbpassword:"app"
 ],
 test:[prop1:"devValue1", prop2:"devValue2"],
 prod:[prop1:"prodValue1", prop2:"prodValue2"]
]
  // define usedProfile as a global then test if it is set from the command line. If not, then set it to dev
def usedProfile
if (project.hasProperty("profile")) {
 usedProfile = project.getProperty("profile")
} else {
 usedProfile = 'dev'
}
  task showProfile << {
 println usedProfile
}
  // Tell processResources to handle this.
processResources{
 expand(profileProperties[usedProfile])
}

When a property is not set in the profileProperties Gradle will stop with:

* What went wrong:
Execution failed for task ':processResources'.
> Could not copy file 'C:\Users\Ron\src\eveasset\src\main\resources\META-INF\per
sistence.xml' to 'C:\Users\Ron\src\eveasset\build\resources\main\META-INF\persis
tence.xml'.

You have to run it with --stackTrace and then search through that to find: * What went wrong: Execution failed for task ‘:processResources’. * What went wrong: Execution failed for task ‘:processResources’. Caused by: groovy.lang.MissingPropertyException: No such property: db for class:

SimpleTemplateScript5

Methinks this might be a tad more userfriendly?


(Sion Williams) #2

Just something to note. Your if-then-else can be accomplished in a much more groovy way:

def usedProfile = project.getProperty("profile") ?: "dev"

It is a simplification of the java ternary operation, and is known as the Elvis operator.

Hope this helps even if not directly relating to the original question.


(ron.smits) #3

That is an excellent idea, maybe I should start reading some groovy stuff :slight_smile:

Thanks.


(ron.smits) #4

so that code actually does not work. Execution stops with

* What went wrong:
A problem occurred evaluating root project 'eveasset'.
> Could not find property 'profile' on root project 'eveasset'.

So I decided to write it the java way and that works

def usedProfile = project.hasProperty("profile") ? project.getProperty("profile"): "dev"