【问题标题】:Exception handling in facade service门面服务中的异常处理
【发布时间】:2017-07-18 18:40:39
【问题描述】:

我正在根据 3tier 架构(Presentation、Application、Domain 层)使用 SpringMVC 开发 Web 应用程序。表示层上还有一个外观服务,从控制器到应用程序服务的每个请求都通过外观服务(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";

外观服务

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

但我不确定是否可以在外观服务中捕获异常,或者是否有更好的解决方案?

【问题讨论】:

    标签: java spring-mvc exception-handling architecture


    【解决方案1】:

    如果帐户服务抛出的异常不是已检查异常,则更好、更简洁的设计是根本不捕获任何异常。使用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;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-11
      • 1970-01-01
      • 1970-01-01
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多