SpringBoot 异常处理返回页面和JSON(两种方式)
2017-12-06 本文已影响83人
sandnul025
springboot controller 中抛出异常会交给默认 /error来进行处理
我们可以将/error 映射到一个特定的controller 替代默认实现
1.重写 /error
@Controller
public class ErrorController extends AbstractErrorController{
public ErrorController(ErrorAttributes errorAttributes) {
super(new DefaultErrorAttributes());
}
@Override
public String getErrorPath() {
return null;
}
private static final String ERROR_PATH = "/error";
private static final int OK = 200;
private static final String ERROR_MESSAGE = "系统内部错误,请联系管理员!";
@RequestMapping(ERROR_PATH)
public ModelAndView ExceptionHandler(HttpServletRequest request,HttpServletResponse response){
// 返回成功状态
response.setStatus(OK);
Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(request, false));
int status = (Integer)model.get("status");
String message = (String)model.get("message");
// 判断请求类型
String header = request.getHeader("X-Requested-With");
boolean isAjax = "XMLHttpRequest".equalsIgnoreCase(header);
switch (status) {
case 404:
return new ModelAndView("error/404");
case 500:
if(isAjax){
Map<String,Object> error = new HashMap<>();
error.put("code", 1);
error.put("message", ERROR_MESSAGE);
writeJson(response,error);
return null;
}else {
return new ModelAndView("error/500","message",ERROR_MESSAGE);
}
default:
if(isAjax){
Map<String,Object> error = new HashMap<>();
error.put("code", 1);
error.put("message", message);
writeJson(response,error);
return null;
}else {
return new ModelAndView("error/error","message",message);
}
}
}
protected void writeJson(HttpServletResponse response,Map<String,Object> error){
try {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(JSON.toJSONString(error));
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.springmvc 统一异常处理
@ControllerAdvice
public class GlobalExceptionHandler {
private static final String ERROR_MESSAGE = "系统内部错误,请联系管理员!";
@ExceptionHandler(value = Exception.class)
public ModelAndView ExceptionHandler(HttpServletRequest request,HttpServletResponse response, Exception e) {
String header = request.getHeader("X-Requested-With");
if("XMLHttpRequest".equalsIgnoreCase(header)){
Map<String,Object> error = new HashMap<>();
error.put("code", 1);
error.put("message", ERROR_MESSAGE);
writeJson(response,error);
return null;
}else {
ModelAndView mv = new ModelAndView("error/500");
mv.addObject("message", ERROR_MESSAGE);
return mv;
}
}
protected void writeJson(HttpServletResponse response,Map<String,Object> error){
try {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(JSON.toJSONString(error));
} catch (IOException e) {
e.printStackTrace();
}
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>404</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
.sos{width: 500px;height: 200px;margin: 300px auto 0px auto;font-family:"微软雅黑 Light", "微软雅黑";}
.sos .nofind{ font-size:18px; color:#666; text-align:center; margin-top:30px;}
.sos .imgdiv{text-align: center;}
</style>
</head>
<body>
<div class="sos">
<div class="imgdiv">
<img src="../../static/images/404.png" th:src="@{/images/404.png}" width="254" height="92" />
</div>
<div class="nofind">啊哦~一不小心闯进了未知领域</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>500</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
.sos{ width:652px; height:92px; position: absolute; top:50%; left:50%; margin-left:-326px; margin-top:-230px; font-family:"微软雅黑 Light", "微软雅黑";}
.sos .errormessage{ font-size:18px; color:#666; text-align:center; margin-top:30px;}
</style>
</head>
<body>
<body>
<div class="sos">
<div><img src="../../static/images/500.png" th:src="@{/images/500.png}" width="652" height="321" /></div>
<div class="errormessage" th:text="${message}" />
</div>
</body>
</body>
</html>
#base.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>测试异常处理</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="../static/css/common.css" th:href="@{/css/common.css}" rel="stylesheet" />
<script src="../static/js/jquery-3.2.1.min.js" th:src="@{/js/jquery-3.2.1.min.js}" type="text/javascript"></script>
<style type="text/css">
.main{
width: 500px;
height: 500px;
margin: 30px auto;
border: 1px black solid;
}
</style>
</head>
<body>
<div class="main">
<p>测试系统内部异常,前端显示问题!</p>
1.ajax请求失败
<input class="ty-btn" value="ajax" onclick="ajax();" type="button"/>
<br/>
<br/>
2.网页请求失败
<input class="ty-btn" value="page" onclick="page();" type="button"/>
</div>
<script type="text/javascript">
function ajax(){
$.post("/test/json",{},function(json,status){
if(status == "success"){
alert(JSON.stringify(json));
}
},"json");
}
function page(){
window.location.href = "/test/page"
}
</script>
</body>
</html>
@Controller
public class TestController{
@RequestMapping("test/base")
public ModelAndView basePage() {
return new ModelAndView("base");
}
@RequestMapping("test/page")
public ModelAndView testPage() {
System.out.println(1/0);
return new ModelAndView("test1");
}
@RequestMapping("test/json")
public ResultHelper testJson() {
System.out.println(1/0);
return ResultHelper.success();
}
}
如果需要打印一些异常信息,完全可以通过request中进行获取。