门面服务中的异常处理

时间:2017-02-27 23:40:05

标签: java spring-mvc exception-handling architecture

我正在根据3层架构(Presentation,Application,Domain layers)使用SpringMVC开发Web应用程序。此外,在表示层上还有一个外观服务,从控制器到应用程序服务的每个请求都通过外观服务(Contorller - > FacadeService - > ApplicationService)。如果我在Application或Domain层中遇到异常,我应该在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;
}

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

1 个答案:

答案 0 :(得分: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;
  }
}