I have a validation for big file size in a try block, after throwing that error its again going and checking the null values of the other attributes of static constraints and throwing that error as well.
How to stop the flow after returning the first error?
here is the code
static constraints = {
applicationName(blank: false, size: 1..25)
applicationShortName(blank: false, size: 1..10)
applicationImage(nullable: false, maxSize: MAX_SIZE)
contentProviderId (
validator: {
if (it == 0) {
return ['notSelected']
}
}
)
customErrorMessage (
validator: {
if ("fileToBig".equals(it)) {
return ['fileToBig']
}
}
)
}
try {
CommonsMultipartFile file = request.getFile('applicationImageUrl');
logger.debug("POSTPROCESS: is file empty=${file.isEmpty()}")
if(!file.isEmpty()) {
try {
-- other logic
}
catch (Exception ex) {
logger.warn("Failed to upload file - improper file type", ex)
return [];
}
logger.debug("Getting new image file")
try {
-- logic
if (file.size <= MAX_SIZE) {
-- logic
} else {
customErrorMessage = "fileToBig"; ( ERROR FOR BIG FILE SIZE)
}
} catch (Exception e) {
logger.warn("Failed to upload file", e)
customErrorMessage = "fileToBig";
}
} else {
logger.debug("File was empty. Will check if there is a file in submission")
if (submission.applicationImage != null && submission.applicationImage != []) {
logger.debug("submission contains applicationImage=${submission.applicationImage}")
this.applicationImage = submission.applicationImage;
}
}
} catch (Exception e) {
this.errors.reject("error","An error occured when uploading file. Please try again.");
logger.error("Failed to upload file", e);
return [];
}
--logic
if (application != null) { //Application already exists!
submission.applicationId = application.id;
return [next: 10];
}
return [];
}
after the big file size error, the application image is not set , so its throwing application image null error as well…
You can add a custom validator to your applicationImage field, to only check for null value if customErrorMessage field is not null.
This way you will only get applicationImage error in validation exception if customErrorMessage is not null.
In validator closure you have access to the value of the field being checked and to the whole object as well:
Thus you can do something like this:
Might need a tweak in error messages but I hope you get my point 😉