第一步: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是先执行,所以执行完后就会显示前端文字信息
基于ajax请求异常捕获
原文地址:https://www.cnblogs.com/houlai/p/9016793.html