2014-01-22 36 views
0

我有一個Spring MVC應用程序,我使用數據綁定來向發佈的值填充自定義窗體對象someForm。控制器的有趣的部分如下所示:如何在Spring MVC中處理驗證和嚴重錯誤

@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類實現泉org.springframework.validation.Validator接口。雖然這對驗證用戶輸入和創建與輸入相關的錯誤消息很有用,但這似乎不太適合處理更嚴重的錯誤,這些錯誤不能呈現給用戶,但仍然與控制器輸入有關,如缺少錯誤隱藏的領域預計將在後期出席。這樣的錯誤應該導致應用程序錯誤。什麼是Spring MVC處理這種錯誤的方法?

回答

2

我通常會這樣做,我不會在DAO和服務層次中捕獲異常。我只是把他們然後我在控制器類和這些的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"; 
    } 
} 
+0

謝謝!因此,在使用Validator之後,我將不得不再次檢查一些重要的驗證錯誤並手動拋出異常(然後由ExceptionHandlers處理),因爲Springs Errors類僅用於爲用戶保留錯誤消息,這些錯誤消息在語義上與應用錯誤? – xSNRG

+0

是的,應用程序錯誤是不同的,因此必須以不同的方式處理。 Spring錯誤類用於解決表單及其後備對象之間的綁定錯誤。只要確保在任何Service-DAO-Controller代碼中都沒有try ... catch塊。 – Bnrdo

+0

非常感謝! – xSNRG