第一步:controller中
@RequestMapping("/ajaxerror")
public String ajaxerror() {
return "thymeleaf/ajaxerror";
}
//一個異常包下的類,一個html,一個js
@RequestMapping("/getAjaxerror")
@ResponseBody
public IMoocJSONResult getAjaxerror() {
int a = 1 / 0;
return IMoocJSONResult.ok();
}
第二步:html中
<!DOCTYPE html >
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
<script th:src="@{/static/js/jquery.min.js}"></script>
</head>
<body>
<h1>測試ajax錯誤異常</h1>
<script th:src="@{/static/js/ajaxerror.js}"></script>
</body>
</html>
標准ajax請求
$.ajax({
url: "/err/getAjaxerror",
type: "POST",
async: false,
success: function(data) {
debugger;
if(data.status == 200 && data.msg == "OK") {
alert("success");
} else {
alert("發生異常:" + data.msg);
}
},
error: function (response, ajaxOptions, thrownError) {
debugger;
alert("error");
}
});
第三步 異常類 在exception包中 IMoocExceptionHandler
詳情參考代碼
第四步 前端請求 http://localhost:8080/err/ajaxerror
結果報異常 alert一下
因js是先執行,所以執行完后就會顯示前端文字信息