1.定义一个自定义异常 继承RunTimeException

    1. public class MyExceprion extends RuntimeException {
    2. private String message;
    3. public MyExceprion() {}
    4. public MyExceprion(String message) {
    5. this.message = message;
    6. }
    7. }

    2.在创建一个异常管理类 实现HandlerExceptionResolver并且通过@Component给Spring管理

    @Component
    public class ExceptionResolver implements HandlerExceptionResolver {
        @Override
      public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
            if (e instanceof MyExceprion){//判断是不是自己定义的异常
                //e.getMessage() 是继承RunTimeException里重写的方法
                modelAndView.addObject("ss",e.getMessage());
                modelAndView.setViewName("exception.jsp");
            }
            return modelAndView;
        }
    }
    

    3.使用

    @Controller
    public class TestController {
        @RequestMapping("hello")
        public String aaa() {
            try {
                String s = null;
                s.length();
            } catch (Exception e) {
                throw new MyExceprion("出现错误");
            }
            return "index.jsp";
        }