请结合springboot学习教程项目github地址 https://github.com/heng1234/spring-boot_one来理解
ErrorController
/**
* 不是ajax形式访问
* @return
*/
@RequestMapping("err")
public String error() {
int res = 1 / 0;
return "/error/error";
}
定义个异常捕捉类:
package com.yh.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.yh.pojo.HlvyJSONResult;
@ControllerAdvice
public class HlvyExceptionHandler {
static final String TO_URL = "/thymeleaf/error/error";
/**
* 捕获不是ajax请求
* @param request
* @param response
* @param e
* @return
* @throws Exception
*/
/* @ExceptionHandler(value= Exception.class)
public Object errExceyion(HttpServletRequest request,HttpServletResponse response,Exception e) throws Exception {
e.printStackTrace();
ModelAndView view = new ModelAndView();
System.out.println("this HlvyExceptionHandler");
view.addObject("e", e);
view.addObject("url", request.getRequestURI());
view.setViewName(TO_URL);
return view;
}*/
}
错误页面:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2 th:text="${e}"></h2>
<h2 th:text="${url}"></h2>
</body>
</html>