1 在src/main/java/com/imooc 新建exception包,在該包下新建AjaxExceptionHandler.java內容如下:
package com.imooc.exception;
import com.imooc.pojo.JSONResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
@RestControllerAdvice
public class AjaxExceptionHandler {
@ExceptionHandler(value = Exception.class)
public JSONResult defaultErrorHandler(HttpServletRequest request,Exception e) throws Exception{
e.printStackTrace();
return JSONResult.errorMsg(e.getMessage());
}
}
2 在src/main/java/com/imooc/contoller/ErrorController.java內容如下:
package com.imooc.contoller;
import com.imooc.pojo.JSONResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("err")
public class ErrorController {
@RequestMapping("/ajaxerror2")
public String ajaxError(){
return "thymeleaf/ajaxerror";
}}
3 src\main\resources\templates\thymeleaf\ajaxerror.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.springframework.org/schema/jdbc">
<head>
<meta charset="UTF-8">
<title>測試ajax錯誤異常</title>
<script src="../js/jquery.min.js" type="text/javascript"></script>
<script src="../js/ajaxerror.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>
4 src\main\resources\static\js\ajaxerror.js
$.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");
}
});
5 src\main\java\com\imooc\contoller\ErrorController.java
package com.imooc.contoller;
import com.imooc.pojo.JSONResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("err")
public class ErrorController {
@RequestMapping("/getAjaxerror")
public JSONResult getAjaxError(){
int a=1/0;
return JSONResult.ok();
}}
根據慕課網學習整理