spring mvc @ExceptionHandler方法得到相同的视图

vin*_*ent 10 java spring spring-mvc exceptionhandler

我的问题是我想创建一个@ExceptionHandler方法来捕获所有未处理的异常.一旦捕获,我想重定向到当前页面而不是指定一个单独的页面只是为了显示错误.

基本上我如何获取somemethod返回的someview的值,并在下面的方法unhandledExceptionHandler中动态设置它.

@ExceptionHandler(Exception.class)
protected ModelAndView unhandledExceptionHandler(Exception ex){
    System.out.println("unhandle exception here!!!");
    ModelAndView mv = new ModelAndView();
    mv.setViewName("currentview");
    mv.addObject("UNHANDLED_ERROR", "UNHANDLED ERROR. PLEASE CONTACT SUPPORT. "+ex.getMessage());
    return mv;
}



@RequestMapping(value = "/somepage", method = RequestMethod.GET)
public String somemethod(HttpSession session) throws Exception {
    String abc = null;
    abc.length();
    return "someview";
}
Run Code Online (Sandbox Code Playgroud)

所以在JSP中,我可以将此错误消息呈现回当前页面.

<c:if test="${not empty UNHANDLED_ERROR}">
    <div class="messageError"> ${UNHANDLED_ERROR}</div>
</c:if>
Run Code Online (Sandbox Code Playgroud)

ams*_*ams 6

我不认为有办法做你要求的,因为在异常处理程序方法中unhandledExceptionHandler,无法找出处理程序方法somemethod将返回的视图名称.

唯一的方法是引入某种元数据方案,这样当你最终进入异常处理程序时,你可以找出将它映射到的视图.但我认为这种元数据方案会相当复杂.您可以通过查找抛出异常时正在访问的原始URL来实现此类方案,这可以通过下面的代码片段来完成.

(ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()
Run Code Online (Sandbox Code Playgroud)

一旦你知道原始请求URL可以重定向到它,可能使用flash属性来存储有异常的事实以及错误是什么.

当您有一个在不同视图之间进行选择的处理程序方法时,将出现元数据的主要问题.

@RequestMapping(value = "/somepage", method = RequestMethod.GET)
public String somemethod(HttpSession session) throws Exception {
    String abc = null;
    if(someCondition) {
        abc.length();
        return "someview";
    } else {
        // do some stuff here.
        return "someOtherView";
    }
}
Run Code Online (Sandbox Code Playgroud)

即使知道某些方法是错误的来源,您也不知道if语句中的哪个分支导致了异常.


Lef*_*hik 5

我不认为你可以在不修改所有处理程序方法的情况下做到这一点.但是,您可以尝试以"漂亮"的方式执行此操作:

1)您可以定义自己的注释,它将接受目标视图名称作为参数(例如@ExceptionView)

2)接下来要做的是用它标记你的处理程序方法,例如:

@ExceptionView("someview")
@RequestMapping(value = "/somepage", method = RequestMethod.GET)
    public String somemethod(HttpSession session) throws Exception {
    String abc = null;
    abc.length();
    return "someview";
}
Run Code Online (Sandbox Code Playgroud)

3)之后你可以在异常处理程序中做这样的事情:

@ExceptionHandler(Exception.class)
protected ModelAndView unhandledExceptionHandler(Exception ex, HandlerMethod hm) {
    String targetView;
    if (hm != null && hm.hasMethodAnnotation(ExceptionView.class)) {
        targetView = hm.getMethodAnnotation(ExceptionView.class).getValue();
    } else {
        targetView = "someRedirectView"; // kind of a fallback
    }
    ModelAndView mv = new ModelAndView();
    mv.setViewName(targetView);
    mv.addObject("UNHANDLED_ERROR", "UNHANDLED ERROR. PLEASE CONTACT SUPPORT. "+ex.getMessage());
    return mv;
}
Run Code Online (Sandbox Code Playgroud)