一 定义控制器
package com.imooc.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.imooc.pojo.IMoocJSONResult; @Controller @RequestMapping("err") public class ErrorController { @RequestMapping("/error") public String error() { int a = 1 / 0; return "thymeleaf/error"; } }
二 定义错误处理类
package com.imooc.exception; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; import com.imooc.pojo.IMoocJSONResult; @ControllerAdvice public class IMoocExceptionHandler { public static final String IMOOC_ERROR_VIEW = "error"; @ExceptionHandler(value = Exception.class) public Object errorHandler(HttpServletRequest reqest, HttpServletResponse response, Exception e) throws Exception { e.printStackTrace(); ModelAndView mav = new ModelAndView(); mav.addObject("exception", e); mav.addObject("url", reqest.getRequestURL()); mav.setViewName(IMOOC_ERROR_VIEW); return mav; } }
三 定义错误页面模板
捕获全局异常发生错误:
四 测试