When scripts are writen they should be written defensively. This means that any situation that is unexpected should be coded for and appropriate action taken.
Defensive Script Writing Throwing an Informative Exception
For example the following script assumes that a UDO named myname exists:
def execute() {
def udoService = flexSdkClient.userDefinedObjectService
def udoObjectQuery = UserDefinedObjectApiQuery.builder()
.name('myname')
.build()
// Should always return a UDO
def udos = udoService.getUserDefinedObjects('reels', udoObjectQuery)
// get the first UDO
def udo = udos.getObjects().find { true }
def assetPl = NewAssetPlaceholder.builder()
.type('media-asset')
.name('demo asset')
.build()
def assetService = flexSdkClient.assetService
def asset = assetService.createAsset(assetPl)
// add the asset as a child to the UDO
udoService.addChildObject('reals', udo.id, asset.id)
}
The problem with this is that if no UDO named myname exists the job will fail with a NullPointerException. A better solution is to throw an exception with a relevant message:
def execute() {
def udoService = flexSdkClient.userDefinedObjectService
def udoObjectQuery = UserDefinedObjectApiQuery.builder()
.name('myname')
.build()
// Should always return a UDO
def udos = udoService.getUserDefinedObjects('reels', udoObjectQuery)
if (udos.totalCount === 0) {
thrownewException("UDO named 'mynane' does not exist")
}
// get the first UDO
def udo = udos.getObjects().find { true }
def assetPl = NewAssetPlaceholder.builder()
.type('media-asset')
.name('demo asset')
.build()
def assetService = flexSdkClient.assetService
def asset = assetService.createAsset(assetPl)
// add the asset as a child to the UDO
udoService.addChildObject('reals', udo.id, asset.id)
}
Defensive programming is especially important when assuming the existence of certain data. For example, if a script performs an asset search and expects a single result, exceptions should be thrown if zero or multiple assets are found.
Defensive Script Writing for Catching Expected Exceptions
If you are expecting data issues, be sure to catch the specific Feign exception in your code when calling methods on Flex SDK services. e.g. if an asset might not have metadata, you can use:
def assetService = flexSdkClient.assetService
try {
assetService.getAssetMetadata(1234L)
} catch (FeignException.NotFound ex) {
....
}
See different type of possible exceptions here - https://github.com/OpenFeign/feign/blob/master/core/src/main/java/feign/FeignException.java#L291
Comments
0 comments
Please sign in to leave a comment.