我有一个Spring MVC应用程序,我使用数据绑定来填充自定义表单对象someForm和发布的值。控制器的有趣部分如下所示:
@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 类正在实现Springs org.springframework.validation.Validator 接口。虽然这对于验证用户输入和创建与输入相关的错误消息非常有用,但这似乎不太适合处理更多关键错误,这些错误无法呈现给用户但仍与控制器输入相关,如缺失预计将在发布时间出现的隐藏字段。此类错误应导致应用程序错误。什么是Spring MVC处理此类错误的方法?
答案 0 :(得分:2)
我通常做的事情,我不会在DAO和服务层面捕获异常。我只是抛出它然后我在Controller类和这些ExceptionHandlers中定义ExceptionHandlers,我把我的代码用于处理这样的错误然后将我的用户重定向到一个类似
的页面发生致命错误。请联系管理员。
以下是ExceptionHandler注释
的示例代码@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";
}
}