一 控制器
package com.imooc.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.imooc.pojo.IMoocJSONResult; @Controller @RequestMapping("err") public class ErrorController { @RequestMapping("/ajaxerror") public String ajaxerror() { return "thymeleaf/ajaxerror"; } @RequestMapping("/getAjaxerror") @ResponseBody public IMoocJSONResult getAjaxerror() { int a = 1 / 0; return IMoocJSONResult.ok(); } }
二 异常处理类
package com.imooc.exception; import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import com.imooc.pojo.IMoocJSONResult; @RestControllerAdvice public class IMoocAjaxExceptionHandler { @ExceptionHandler(value = Exception.class) public IMoocJSONResult defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception { e.printStackTrace(); return IMoocJSONResult.errorException(e.getMessage()); } }
三 错误页面模板
测试ajax错误异常
四 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"); } });
五 测试