0

在我当前的 spring-boot 项目中,我有这个 ExceptionHandler:

@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception error) throws Exception {
        if (AnnotationUtils.findAnnotation(error.getClass(), ResponseStatus.class) != null)
            throw error;

        ModelAndView mav = new ModelAndView();
        mav.setAttribute("error", error);
        return mav;
    }

}

我想做的是让这个处理程序重定向到不同的错误页面,这取决于错误的来源。

我的项目中有两种“类型”的页面:一种是公共的,由匿名用户或经过身份验证的用户访问,另一种是管理页面(私有),只有经过身份验证的用户才能访问。

这两种类型的页面有不同的样式。我希望,当用户在公共页面时发生错误时,会显示一个具有公共样式的错误页面。如果用户在私人页面时发生错误,则会显示另一个错误页面,该页面具有私人页面的样式。

4

2 回答 2

0

您可以选择需要在控制器中抛出的异常类,假设如下:

@RequestMapping(value = "/check")
 public ModelAndView processUser( ) throws Exception {
        ModelAndView modelAndView = new ModelAndView();

        if (something... ) {
            throw new GlobalDefaultExceptionHandler( );  // throws GlobalDefaultExceptionHandler
        }
        if (something else... ) {
            throw new AnotherExceptionHandler( );// throws 'anotherExceptionHandler'
        }

     // If there isn't exception thrown....do something

 }

并假设这是AnotherExceptionHandler类:

@ControllerAdvice
public class AnotherExceptionHandler{

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception error) throws Exception {
        if (AnnotationUtils.findAnnotation(error.getClass(), ResponseStatus.class) != null)
            throw error;

        // Go to another view
        ModelAndView mav = new ModelAndView();
        mav.setAttribute("anotherError", error);
        return mav;
    }

}

但是如果你被迫只使用一个处理程序,你可以直接使用选择:

@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception error) throws Exception {

 ModelAndView mav =null;

        if ( // something...){
         mav = new ModelAndView()
         mav.setAttribute("error", ... );
         return mav;
          } 

         else if (// another something...){
           mav = new ModelAndView()
           mav.setAttribute("anotherError", ...);
           return mav;
          }

return mav;

}
于 2015-09-08T14:00:42.000 回答
0

有几种选择。他们之中有一些是:

  1. 您可以使用 . 检查用户是否已通过身份验证request.getUserPrincipal()null如果用户未通过身份验证,则返回值。根据结果​​,您可以返回不同的视图。

  2. 让您的所有控制器服务公共页面从一个 PublicBaseController 扩展,控制器服务私有页面扩展 PrivateBaseController。将带有注释的方法添加@ExceptionHandler到返回适当视图的基本控制器。

于 2015-09-08T14:55:21.300 回答