如何使用SpringMVC进行异常处理

在Struts2中咱们能够定义全局异常而后跳转到对用户友好的错误提示页面。在SpringMVC中咱们依然能够。java

1.仅处理当前Action(SpringMVC里说的是Handler)里的异常:

//在当前Handler里写一个处理异常的方法而且加上注解 @ExceptionHandler
    //value值表示能够处理哪些异常及其子类异常
    @ExceptionHandler(value = {ArithmeticException.class})
    public String handExceptionForHelloAction(Exception e) {
        System.out.println("出异常啦!");
        //定义跳转的出错页面
        return "error";
    }

    //测试@ExceptionHandler异常处理
    @RequestMapping("errortest")
    public ModelAndView testError(
            @RequestParam("num")
                    int num, ModelAndView modelAndView) {
        System.out.println("10/" + num + "=" + 10 / num);
        modelAndView.addObject("msg", "Successful!");
        modelAndView.setViewName("success");
        return modelAndView;
    }

当请求方法是http://localhost:8080/SSMProjectMaven/hello/errortest.do?num=10时,测试结果以下:app

当请求方法是http://localhost:8080/SSMProjectMaven/hello/errortest.do?num=0时,测试结果以下:测试

若是咱们想要在页面中输出错误信息能够使用ModelAndView:spa

//在当前Handler里写一个处理异常的方法而且加上注解 @ExceptionHandler
    //value值表示能够处理哪些异常及其子类异常
    @ExceptionHandler(value = {ArithmeticException.class})
    public ModelAndView handExceptionForHelloAction(Exception e) {
        System.out.println("出异常啦!");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("exception", e.getMessage());
        modelAndView.setViewName("error");
        //定义跳转的出错页面
        return modelAndView;
    }

当请求方法是http://localhost:8080/SSMProjectMaven/hello/errortest.do?num=0时,测试结果以下:code

 

注意:这里不能在处理异常的方法的入参里加入ModelAndView或者Map,即不能这样:对象

2.处理全部Handler的异常

写一个处理专门处理异常的类:继承

在类的上添加@ControllerAdvice注解get

@ControllerAdvice
public class HandleAllException {
    @ExceptionHandler(value = {ArithmeticException.class})
    public ModelAndView handExceptionForHelloAction(Exception e) {
        System.out.println("出异常啦!");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("exception", e.getMessage());
        modelAndView.setViewName("error");
        //定义跳转的出错页面
        return modelAndView;
    }
}

在SpringMVC配置文件中要配置扫描到该类的包,我这个类是放在at.flying.exceptionhandler包中的,因此添加以下的信息:源码

测试的方法及测试结果同上。it

NOTICE:

• 主要处理 Handler 中用 @ExceptionHandler 注解定义的方法。
• @ExceptionHandler 注解定义的方法优先级问题:例如发
生的是NullPointerException,可是声明的异常有
RuntimeException 和 Exception,此候会根据异常的最近
继承关系找到继承深度最浅的那个 @ExceptionHandler
注解方法,即标记了 RuntimeException 的方法
• ExceptionHandlerMethodResolver 内部若找不
到@ExceptionHandler 注解的话,会找
@ControllerAdvice 中的@ExceptionHandler 注解方法

3.使用SimpleMappingExceptionResolver对全部异常进行统一处理

 

采用这种方式SpringMVC会把异常对象放入request域中,key就是exceptionAttribute里设置的值,该值默认是exception.

源码以下:

测试方法同上,测试结果以下:

相关文章
相关标签/搜索