1 在src/main/java/com/imooc 新建exception包,在该包下新建MyExceptionHandler.java内容如下:
package com.imooc.contoller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
package com.imooc.exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ControllerAdvice
public class MyExceptionHandler {
public static final String ERROR_VIEW="error";
@ExceptionHandler(value = Exception.class)
public Object errorHandler(HttpServletRequest request, HttpServletResponse response,Exception e) throws Exception{
ModelAndView mav=new ModelAndView();
mav.addObject("exception",e);
mav.addObject("url",request.getRequestURI());
mav.setViewName(ERROR_VIEW);
return mav;
}
}
2 在src/main/resources/templates文件夹先新建error.html,内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>捕获全局异常</title>
</head>
<body><h1 style="color:red">发生错误:</h1>
错误信息为:<p th:text="${exception.message}"></p>
错误页面为:<p th:text="${url}"></p>
</body>
</html>
3 随便在contoller里抛出一个错误,例如 :
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190401055125187.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1RvcmV5X0xp,size_16,color_FFFFFF,t_70)
4 结果展示:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190401055157991.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1RvcmV5X0xp,size_16,color_FFFFFF,t_70)
根据慕课网学习整理