Reputation: 1208
I seek the best way to handle error validation in the @service layer in a spring mvc application.
I have a @Controller and a @Service class.
My controller :
public String saveProduct(Product product) {
myService.saveProduct(product);
return "view";
}
My service :
public void saveProduct(Product product) {
// some validation here
myDao.save(product);
}
Now let's say that the validation leads to 2 or 3 errors (the color is not appropriate, the supplier can't deliver the product right now, and so on...) and I have to display all of them at the same time.
How do I transmit those errors to my controller, and then to my jsp ? Using an "Errors" object ? An exception containing all those errors ?
I've already looked here : Passing errors back to the view from the service layer but I can't find a convenient answer. Do I really have to create unchecked exceptions for EACH error ? And what if I have a 20 or 30 errors ?
Upvotes: 3
Views: 3876
Reputation: 1208
Finally I created a custom exception to handle the functional errors :
public class ServiceException extends Exception {
private List<String> errors = new ArrayList<>();
(...)
}
I also created a ValidationErrorsHelper class with the following method :
public static void rejectErrors(final BindingResult result, final List<String> errors) {
if (errors != null) {
for (final String error : errors) {
result.reject(error);
}
}
}
And in my controller class, I catch the exception :
try {
this.myService.myFunction(...);
} catch (final ServiceException e) {
ValidationErrorsHelper.rejectErrors(result, e.getErrors());
}
This is the best way I could find. If there's any better suggestion I'm all ears !
Upvotes: 4