springboot controller 中拋出異常會交給默認 /error來進行處理
我們可以將/error 映射到一個特定的controller 替代默認實現(xiàn)
1.重寫 /error
@Controller
public class ErrorController extends AbstractErrorController{
public ErrorController(ErrorAttributes errorAttributes) {
super(new DefaultErrorAttributes());
}
@Override
public String getErrorPath() {
return null;
}
private static final String ERROR_PATH = "/error";
private static final int OK = 200;
private static final String ERROR_MESSAGE = "系統(tǒng)內(nèi)部錯誤,請聯(lián)系管理員!";
@RequestMapping(ERROR_PATH)
public ModelAndView ExceptionHandler(HttpServletRequest request,HttpServletResponse response){
// 返回成功狀態(tài)
response.setStatus(OK);
Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(request, false));
int status = (Integer)model.get("status");
String message = (String)model.get("message");
// 判斷請求類型
String header = request.getHeader("X-Requested-With");
boolean isAjax = "XMLHttpRequest".equalsIgnoreCase(header);
switch (status) {
case 404:
return new ModelAndView("error/404");
case 500:
if(isAjax){
Map<String,Object> error = new HashMap<>();
error.put("code", 1);
error.put("message", ERROR_MESSAGE);
writeJson(response,error);
return null;
}else {
return new ModelAndView("error/500","message",ERROR_MESSAGE);
}
default:
if(isAjax){
Map<String,Object> error = new HashMap<>();
error.put("code", 1);
error.put("message", message);
writeJson(response,error);
return null;
}else {
return new ModelAndView("error/error","message",message);
}
}
}
protected void writeJson(HttpServletResponse response,Map<String,Object> error){
try {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(JSON.toJSONString(error));
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.springmvc 統(tǒng)一異常處理
@ControllerAdvice
public class GlobalExceptionHandler {
private static final String ERROR_MESSAGE = "系統(tǒng)內(nèi)部錯誤,請聯(lián)系管理員!";
@ExceptionHandler(value = Exception.class)
public ModelAndView ExceptionHandler(HttpServletRequest request,HttpServletResponse response, Exception e) {
String header = request.getHeader("X-Requested-With");
if("XMLHttpRequest".equalsIgnoreCase(header)){
Map<String,Object> error = new HashMap<>();
error.put("code", 1);
error.put("message", ERROR_MESSAGE);
writeJson(response,error);
return null;
}else {
ModelAndView mv = new ModelAndView("error/500");
mv.addObject("message", ERROR_MESSAGE);
return mv;
}
}
protected void writeJson(HttpServletResponse response,Map<String,Object> error){
try {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(JSON.toJSONString(error));
} catch (IOException e) {
e.printStackTrace();
}
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>404</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
.sos{width: 500px;height: 200px;margin: 300px auto 0px auto;font-family:"微軟雅黑 Light", "微軟雅黑";}
.sos .nofind{ font-size:18px; color:#666; text-align:center; margin-top:30px;}
.sos .imgdiv{text-align: center;}
</style>
</head>
<body>
<div class="sos">
<div class="imgdiv">
<img src="../../static/images/404.png" th:src="@{/images/404.png}" width="254" height="92" />
</div>
<div class="nofind">啊哦~一不小心闖進了未知領(lǐng)域</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>500</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
.sos{ width:652px; height:92px; position: absolute; top:50%; left:50%; margin-left:-326px; margin-top:-230px; font-family:"微軟雅黑 Light", "微軟雅黑";}
.sos .errormessage{ font-size:18px; color:#666; text-align:center; margin-top:30px;}
</style>
</head>
<body>
<body>
<div class="sos">
<div><img src="../../static/images/500.png" th:src="@{/images/500.png}" width="652" height="321" /></div>
<div class="errormessage" th:text="${message}" />
</div>
</body>
</body>
</html>
#base.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>測試異常處理</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="../static/css/common.css" th:href="@{/css/common.css}" rel="stylesheet" />
<script src="../static/js/jquery-3.2.1.min.js" th:src="@{/js/jquery-3.2.1.min.js}" type="text/javascript"></script>
<style type="text/css">
.main{
width: 500px;
height: 500px;
margin: 30px auto;
border: 1px black solid;
}
</style>
</head>
<body>
<div class="main">
<p>測試系統(tǒng)內(nèi)部異常,前端顯示問題!</p>
1.ajax請求失敗
<input class="ty-btn" value="ajax" onclick="ajax();" type="button"/>
<br/>
<br/>
2.網(wǎng)頁請求失敗
<input class="ty-btn" value="page" onclick="page();" type="button"/>
</div>
<script type="text/javascript">
function ajax(){
$.post("/test/json",{},function(json,status){
if(status == "success"){
alert(JSON.stringify(json));
}
},"json");
}
function page(){
window.location.href = "/test/page"
}
</script>
</body>
</html>
@Controller
public class TestController{
@RequestMapping("test/base")
public ModelAndView basePage() {
return new ModelAndView("base");
}
@RequestMapping("test/page")
public ModelAndView testPage() {
System.out.println(1/0);
return new ModelAndView("test1");
}
@RequestMapping("test/json")
public ResultHelper testJson() {
System.out.println(1/0);
return ResultHelper.success();
}
}
如果需要打印一些異常信息,完全可以通過request中進行獲取。