Let's imagine, that we have a process, which accepts data of the following type:
{"date":"2014-05-05", "url":"http://some.website.com","counter":3}
- This data should be validated formally: value of
date
should be a parseable date,url
should also conform the normal url syntax. - Also, this data should be validated logically:
date
should be in the future,url
should be an accessible address, returning200 OK
.
To make it clean, one must separate those two validation routines into different units (classes, utils, whatever). The desired final behaviour, however, must give user clear understanding of ALL violations, that are present in data. Something like:
{"Errors":[
"Specified date is not in the future",//Formal validation failed
"Specified URL has invalid syntax"//Logical validation failed
]}
- I have seen some implementations of the required behaviour, but they
use those make use of
Error
objects and are full of checks likeError.hasErrors()
orerror==null
, which does not look elegant. - I have also seen the implementation of
javax.validation
, which gives you all violations on all field at once. Same approach could be implemented for content validation, but I am not sure, that this is the best way to do this.
Question: what is the best practice for handling multiple exceptions/violations of various nature?
UPD: short digest of answers: collect Violations
, build an Exception
, containing their context, cause and description, use an interceptor to render. See reference links from answers:
http://beanvalidation.org/1.0/spec/ JSR 303 specification
http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/validation.html Spring Bean Validation
http://docs.oracle.com/javaee/6/tutorial/doc/gircz.html Java EE validation