2017-02-27 77 views
0

我正在根據3層架構(演示,應用程序,域層)使用SpringMVC開發web應用程序。在表示層上還有一個Facade服務,並且每個從控制器到應用程序服務的請求都通過Facade服務(Contorller - > FacadeService - > ApplicationService)。如果我在應用程序或域圖層中遇到異常,我應該在UI中顯示它。這就是現在如何實施的。門面服務中的異常處理

控制器

@PostMapping("/password/change") 
public String processChangePasswordRequest(ChangePasswordForm form, BindingResult bindingResult){ 
    ChangePasswordReqStatus status = facadeService.requestChangePassword(
      form.getOld(), 
      form.getPassword() 
    ); 

    if(status == ChangePasswordReqStatus.PASSWORD_MISMATCH) 
     bindingResult.rejectValue("oldPassword", "password.mismatch", "Wrong password"); 
    return "change_password"; 

FacadeService

@Override 
public ChangePasswordReqStatus requestChangePassword(Password old, Password password) { 
    try{ 
     accountService.changePassword(old, password); 
    }catch (PasswordMismatchException ex){ 
     return ChangePasswordReqStatus.PASSWORD_MISMATCH; 
    } 
    return ChangePasswordReqStatus.OK; 
} 

但我不知道閹我能趕上在門面服務異常或也許有更好的解決辦法?

回答

0

如果帳戶服務拋出的異常不是檢查異常,更好和更清潔的設計就是根本不捕捉任何異常。使用ControllerAdvice並處理所有異常以及響應邏輯(返回什麼響應狀態,以及消息等)。

你可以做這樣的事情:

@ControllerAdvice 
class GlobalDefaultExceptionHandler { 
    public static final String DEFAULT_ERROR_VIEW = "error"; 

    @ExceptionHandler(value = Exception.class) 
    public ModelAndView 
    defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception { 
    // If the exception is annotated with @ResponseStatus rethrow it and let 
    // the framework handle it - like the OrderNotFoundException example 
    // at the start of this post. 
    // AnnotationUtils is a Spring Framework utility class. 
    if (AnnotationUtils.findAnnotation 
       (e.getClass(), ResponseStatus.class) != null) 
     throw e; 

    // Otherwise setup and send the user to a default error-view. 
    ModelAndView mav = new ModelAndView(); 
    mav.addObject("exception", e); 
    mav.addObject("url", req.getRequestURL()); 
    mav.setViewName(DEFAULT_ERROR_VIEW); 
    return mav; 
    } 
}