0

我有一个 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 方法是什么?

4

1 回答 1

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";
    }
}
于 2014-01-22T08:06:55.577 回答