spring的异常处理分类

方法1
1,简单一次处理 在controller创建一个异常处理方法,并添加@ExceptionHandler

    /**
         * ---------------------异常处理---------------
         */
    
        @ExceptionHandler
        public ModelAndView handlerException(Exception ex) {
            ModelAndView mv=new ModelAndView();
            mv.addObject("exception", ex);
            mv.setViewName("error");
            return mv;
        }

注意:不能使用Map传值,Map不能携带一个对象

2,错误页面
isErrorPage="true"

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isErrorPage="true" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%= exception.getMessage() %>
${exception.message }
</body>
</html>

方法2

可以为exceptionHandler添加一个参数
来添加一个参数专门指定某种类型的异常,可以根据自己的项目要求来指定不同的异常类型指定的异常页面

@ExceptionHandler(RuntimeException.class)
        public ModelAndView handlerException(Exception ex) {
            ModelAndView mv=new ModelAndView();
            mv.addObject("exception", ex);
            mv.setViewName("runtimeerror");
            return mv;
        }


 

发布了4 篇原创文章 · 获赞 0 · 访问量 19

猜你喜欢

转载自blog.csdn.net/luojiawen208/article/details/104977874