上节已经接入Thymeleaf和AOP,但是对于不存在的页面以及API调用,还是会返回不友好的信息,需要对异常及错误,统一进行处理。
A、关闭SpringBoot默认的错误页面
# 关闭SpringBoot的错误空白页面
server.error.whitelabel.enabled=false
![14df3bb78e4164f4d6631e7ddb9ee6b5.png](https://i-blog.csdnimg.cn/blog_migrate/5ec65a16d4650422998fa5ca5e9e9579.png)
B、添加AppErrorController继承自ErrorController,对HTML(页面)请求进行统一响应
对HTML(页面)错误统一处理,重定向到错误页面路径,增加错误页面RequestMapping,返回统一错误页面。
@Controller
public class BasicErrorController implements ErrorController
{
private static final String ERROR_PATH = "/error";
@Override
public String getErrorPath()
{
return ERROR_PATH;
}
/**
* Web页面错误处理
*/
@RequestMapping(value = ERROR_PATH, produces = "text/html")
public String errorPageHandler(HttpServletRequest request, HttpServletResponse response)
{
int status = response.getStatus();
switch (status)
{
case 403:
return "403";
case 404:
return "404";
case 500:
return "500";
default:
return "index";
}
}
}
![2a2cdda84f60375850440cafc9e4577f.png](https://i-blog.csdnimg.cn/blog_migrate/1a62030925e0957e411dfde1555d4daa.png)
C、添加对接口调用的统一返回
private ErrorAttributes errorAttributes;
@Autowired
public BasicErrorController(ErrorAttributes errorAttributes)
{
this.errorAttributes = errorAttributes;
}
/**
* 除Web页面外的错误处理,比如Json/XML等
*/
@RequestMapping(value = ERROR_PATH)
@ResponseBody
public ApiResponse errorApiHandler(HttpServletRequest request)
{
WebRequest webRequest = new ServletWebRequest(request);
Map<String, Object> attr = this.errorAttributes.getErrorAttributes(webRequest, false);
int status = getStatus(request);
return ApiResponse.createMsg(status, String.valueOf(attr.getOrDefault("msg", "error")));
}
private int getStatus(HttpServletRequest request)
{
Integer status = (Integer)request.getAttribute("javax.servlet.error.status_code");
if (status != null)
{
return status;
}
return 500;
}
![9cd19f180b99aca3fa677ec091597fff.png](https://i-blog.csdnimg.cn/blog_migrate/072aefbc69930049dbef66be4650a3dc.png)
参考:
https://my.oschina.net/u/3574106/blog/1823125