2017-02-27 124 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; 
    } 
}