Each_other
2019-12-07 14:49
$.ajax({
url:"/ErrorController/ajaxError",
type:"POST",
async:false,
success:function (data) {
if (data.status ==200 && data.msg == "OK"){
alert("succcess");
} else{
alert("error:" +data.msg);
}
},
error: function (response,ajaxOptions,thrownError) {
alert("error");
}
});handler.java
@RestController
public class AjaxExceptionHandler {
@ExceptionHandler(value = Exception.class)
public JSONResult defaultExceptionHandler(HttpServletRequest request,Exception e) throws Exception{
e.printStackTrace();
return JSONResult.errorException(e.getMessage());
}
}ajaxError.html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>异常捕获</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h1>测试ajax错误异常</h1>
<script th:src="@{/js/ajaxerror.js}"></script>
</body>
</html>controller里面的代码:
@RequestMapping("/testAjaxError")
public String testAjaxError(){
return "/thymeleaf/ajaxError";
}
@RequestMapping("/ajaxError")
@ResponseBody
public JSONResult ajaxError(){
int a=1/0;
return JSONResult.ok();
}
将类注解
@ControllerAdvice
改成
@RestControllerAdvice
就好了
AjaxExceptionHandler类上没有加@controlleradvice注解,可能异常统一处理并未生效,导致进入了error function
SpringBoot开发常用技术整合
102207 学习 · 530 问题
相似问题