24

We all know, that Spring MVC integrate well with Hibernate Validator and JSR-303 in general. But Hibernate Validator, as someone said, is something for Bean Validation only, which means that more complex validations should be pushed to the data layer. Examples of such validations: business key uniqueness, intra-records dependence (which is usually something pointing at DB design problems, but we all live in an imperfect world). Even simple validations like string field length may be driven by some DB value, which makes Hibernate Validator unusable.

So my question is, is there something Spring or Hibernate or JSR offers to perform such complex validations? Is there some established pattern or technology piece to perform such a validation in a standard Controller-Service-Repository setup based on Spring and Hibernate?

UPDATE: Let me be more specific. For example, there's a form which sends an AJAX save request to the controller's save method. If some validation error occurs -- either simple or "complex" -- we should get back to the browser with some json indicating a problematic field and associated error. For simple errors I can extract the field (if any) and error message from BindingResult. What infrastructure (maybe specific, not ad-hoc exceptions?) would you propose for "complex" errors? Using exception handler doesn't seem like a good idea to me, because separating single process of validation between save method and @ExceptionHandler makes things intricate. Currently I use some ad-hoc exception (like, ValidationException):

public @ResponseBody Result save(@Valid Entity entity, BindingResult errors) {
    Result r = new Result();
    if (errors.hasErrors()) {
        r.setStatus(Result.VALIDATION_ERROR);     
        // ...   
    } else {
        try {
            dao.save(entity);
            r.setStatus(Result.SUCCESS);
        } except (ValidationException e) {
            r.setStatus(Result.VALIDATION_ERROR);
            r.setText(e.getMessage());
        }
    }
    return r;
}

Can you offer some more optimal approach?

Jerome Dalbert
  • 10,067
  • 6
  • 56
  • 64
Andrey Balaguta
  • 1,308
  • 2
  • 21
  • 28

1 Answers1

44

Yes, there is the good old established Java pattern of Exception throwing.
Spring MVC integrates it pretty well (for code examples, you can directly skip to the second part of my answer).

What you call "complex validations" are in fact exceptions : business key unicity error, low layer or DB errors, etc.


Reminder : what is validation in Spring MVC ?

Validation should happen on the presentation layer. It is basically about validating submitted form fields.

We could classify them into two kinds :

1) Light validation (with JSR-303/Hibernate validation) : checking that a submitted field has a given @Size/@Length, that it is @NotNull or @NotEmpty/@NotBlank, checking that it has an @Email format, etc.

2) Heavy validation, or complex validation are more about particular cases of field validations, such as cross-field validation :

  • Example 1 : The form has fieldA, fieldB and fieldC. Individually, each field can be empty, but at least one of them must not be empty.
  • Example 2 : if userAge field has a value under 18, responsibleUser field must not be null and responsibleUser's age must be over 21.

These validations can be implemented with Spring Validator implementations, or custom annotations/constraints.

Now I understand that with all these validation facilites, plus the fact that Spring is not intrusive at all and lets you do anything you want (for better or for worse), one can be tempted to use the "validation hammer" for anything vaguely related to error handling.
And it would work : with validation only, you check every possible problem in your validators/annotations (and hardly throw any exception in lower layers). It is bad, because you pray that you thought about all the cases. You don't leverage Java exceptions that would allow you to simplify your logic and reduce the chance of making a mistake by forgetting to check that something had an error.

So in the Spring MVC world, one should not mistake validation (that is to say, UI validation) for lower layer exceptions, such has Service exceptions or DB exceptions (key unicity, etc.).


How to handle exceptions in Spring MVC in a handy way ?

Some people think "Oh god, so in my controller I would have to check all possible checked exceptions one by one, and think about a message error for each of them ? NO WAY !". I am one of those people. :-)

For most of the cases, just use some generic checked exception class that all your exceptions would extend. Then simply handle it in your Spring MVC controller with @ExceptionHandler and a generic error message.

Code example :

public class MyAppTechnicalException extends Exception { ... }

and

@Controller
public class MyController {

    ...

    @RequestMapping(...)
    public void createMyObject(...) throws MyAppTechnicalException {
        ...
        someServiceThanCanThrowMyAppTechnicalException.create(...);
        ...
    }

    ...

    @ExceptionHandler(MyAppTechnicalException.class)
    public String handleMyAppTechnicalException(MyAppTechnicalException e, Model model) {

        // Compute your generic error message/code with e.
        // Or just use a generic error/code, in which case you can remove e from the parameters
        String genericErrorMessage = "Some technical exception has occured blah blah blah" ;

        // There are many other ways to pass an error to the view, but you get the idea
        model.addAttribute("myErrors", genericErrorMessage);

        return "myView";
    }

}

Simple, quick, easy and clean !

For those times when you need to display error messages for some specific exceptions, or when you cannot have a generic top-level exception because of a poorly designed legacy system you cannot modify, just add other @ExceptionHandlers.
Another trick : for less cluttered code, you can process multiple exceptions with

@ExceptionHandler({MyException1.class, MyException2.class, ...})
public String yourMethod(Exception e, Model model) {
    ...
}

Bottom line : when to use validation ? when to use exceptions ?

  • Errors from the UI = validation = validation facilities (JSR-303 annotations, custom annotations, Spring validator)
  • Errors from lower layers = exceptions

When I say "Errors from the UI", I mean "the user entered something wrong in his form".

References :

Community
  • 1
  • 1
Jerome Dalbert
  • 10,067
  • 6
  • 56
  • 64
  • Jerome, thank you for your time. Please see the updated question, I added some details. Could you give your opinion on it? – Andrey Balaguta Sep 30 '12 at 19:55
  • I've read your update and it doesn't change the basic content of my answer. With @ExceptionHandler you don't separate the process of validation, because exception handling is not validation. In a good app, I think you should handle validation AND exceptions : they are technically two different things. So there is no separation, and things are not intricate. Now, if you happen to do the same treatments in validation handling and exception handling, I advise you to write a method such as "processError(...)" that would be called by both parts. Hope this helps, I cannot say much more I think – Jerome Dalbert Sep 30 '12 at 20:51
  • Still, I can't understand how are they "technically two different things" if they come to the same end (validation message shown to the user) and come from the same beginning (user typing invalid data)? Suppose I have not a single method, but *two* methods which can throw this ValidationException (one being save, another one -- delete, deletion may fail due to non-system error) and they both return differently structured JSON. How would I discern which view to return inside the @ExceptionHandler? – Andrey Balaguta Oct 01 '12 at 05:24
  • They are two different things because these are not validation : DB error because the base is full, the element to update doesn't exist in DB, a webservice your controller depends on is offline or has a problem, a service cannot create a file because somehow the rights on the folder have been changed, and any other exception I don't have in mind right now : for most of those cases you want to warn the user that "some unexpected error happened". As for your example, you can make the difference with a SaveException and a DeleteException that you would handle with two different @ExceptionHandler. – Jerome Dalbert Oct 01 '12 at 06:51
  • By the way, if your user typed invalid data, you shouldn't handle this with a ValidationException but with @Valid and/or custom constraints and/or custom Spring validators (most of the time). These facilities do not usually throw exception. – Jerome Dalbert Oct 01 '12 at 06:55
  • 3
    Simple example - business key uniqueness check, not a system error like "the base is full", but more or less the same as `@NotNull` check *still* it requires complex processing like DB hit. Where would you put this check? If in `@ExceptionHandler` then I can't understand why separate it from the `BindingResult` check. A developer would expect to find all validation steps grouped (or at least chained) together. Putting them into separate methods would require additional mental effort if controller is big (like, "where does that validation message come from?! not from BindingResult!"). – Andrey Balaguta Oct 01 '12 at 17:50
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/17410/discussion-between-andy-and-jerome-dalbert) – Andrey Balaguta Oct 01 '12 at 18:19