Question

I have a Spring MVC application where I use data binding to populate a custom form object someForm with the posted values. The interesting part of the controller looks like the following:

@RequestMapping(value = "/some/path", method = RequestMethod.POST)
public String createNewUser(@ModelAttribute("someForm") SomeForm someForm, BindingResult result){
    SomeFormValidator validator = new SomeFormValidator();
    validator.validate(someForm, result);

    if(result.hasErrors()){
        ...

        return "/some/path";
    }
}

SomeFormValidator class is implementing Springs org.springframework.validation.Validator interface. While this is great for validating the users input and creating error messages related to the input, this seems to be not well suited to handle more critical errors, which cannot be presented to the user but are still related to a controller input, like a missing hidden field which is expected to be present at post time. Such errors should result in application errors. What is the Spring MVC way to handle such errors?

Was it helpful?

Solution

What I usually do, I dont catch exceptions in the DAO and Service layes. I just throw them then I define ExceptionHandlers in the Controller class and in these ExceptionHandlers, I put my codes for handling such errors then redirect my users to a page saying something like

Fatal Error Occured. Please contact the administrators.

Here is the sample code of ExceptionHandler annotation

@Controller
public class MyController {

    @Autowired
    protected MyService myService;

    //This method will be executed when an exception of type SomeException1 is thrown
    //by one of the controller methods
    @ExceptionHandler(SomeException1.class)
    public String handleSomeException1(...) {
        //...
        //do some stuff
        //...

        return "view-saying-some-exception-1-occured";
    }

    //This method will be executed when an exception of type SomeException2 is thrown
    //by one of the controller methods
    @ExceptionHandler(SomeException2.class)
    public String handleSomeException2(...) {
        //...
        //do some stuff
        //...

        return "view-saying-some-exception-2-occured";
    }


    //The controller method that will entertain request mappings must declare 
    //that they can throw the exception class that your exception handler catches
    @RequestMapping(value = "/someUrl.htm", method = RequestMethod.POST)
    public String someMethod(...) throws SomeException1, SomeException2{

        //...
        //do some stuff, call to myService maybe
        //...

        return "the-happy-path-view-name";
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top