package com.example.exception; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Configuration public class GlobalException implements HandlerExceptionResolver { /** * 全局异常处理 (自动指向页面,并自动分配异常数据到模板中) * * @param httpServletRequest * @param httpServletResponse * @param o * @param e * @return */ @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { ModelAndView modelAndView = new ModelAndView(); if (e instanceof ArithmeticException) {// 数字异常 modelAndView.setViewName("error/error1"); } if (e instanceof NullPointerException) {// 空指钊异常 modelAndView.setViewName("error/error2"); } if (e instanceof NoHandlerFoundException) {//404 modelAndView.setViewName("error/404"); } modelAndView.addObject("error", e.toString()); return modelAndView; } }