- SpringBoot设计,如果出现错误404或500,自动调用特定路径下的html页面(路径和名字都特定)。
/templates/error/404.html
、/templates/error/500.html
。程序中有错误自动就调用该页面。 - 但是错误有异步请求错误,也想同时记录日志。则使用统一处理的方式,即全局配置。使用
HomeController,加获取错误页面的请求,手动重定向路径。
@RequestMapping(path = "/error", method = RequestMethod.GET)
public String getErrorPage() {
return "/error/500";
}
在Controller下新建advice通知配置包,新建ExceptionAdvice。用到两个注解:@ControllerAdvice
,@ExceptionHandler
。
- 是Controller全局配置类,不用对任何Controller再做配置,可以统一做Controller的全局配置。
@ControllerAdvice
用来修饰类。 - 异常处理方案
@ExceptionHandler
、绑定数据方案@ModelAttribute
、绑定参数方案@DataBinder
. 他们都用来修饰方法。 - 这里只演示,统一处理异常(
@ExceptionHandler
)
// 是Controller全局配置类,不用对任何Controller再做配置,可以统一做Controller的全局配置。@ControllerAdvice用来修饰类。
// 异常处理方案@ExceptionHandler、绑定数据方案@ModelAttribute、绑定参数方案@DataBinder. 他们都用来修饰方法。
// 这里只演示,统一处理异常(@ExceptionHandler)
@ControllerAdvice(annotations = Controller.class) // 限定注解@Controller,否则组件扫描所有的bean
public class ExceptionAdvice {
private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
@ExceptionHandler({Exception.class})// 处理哪些异常?Exception是所有异常的父类,所有异常都处理
// 有异常controller会传过来Exception
public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
// 记录日志
logger.error("服务器发生异常:" + e.getMessage());//异常的概括
for (StackTraceElement element : e.getStackTrace()) {//把异常所有栈的信息都记录下来
logger.error(element.toString());
}
// 给浏览器响应
// 要看是什么请求,想要服务器返回网页html/异步请求JSON(xml).从请求的消息头获取。
String xRequestedWith = request.getHeader("x-requested-with");
if ("XMLHttpRequest".equals(xRequestedWith)) {// 异步请求
response.setContentType("application/plain;charset=utf-8");
PrintWriter writer = response.getWriter();// 输出流
writer.write(CommunityUtil.getJSONString(1,"服务器异常!"));// 输出JSON字符串
}else{// 请求html,重定向到错误页面
response.sendRedirect(request.getContextPath() + "/error");
}
}
}
点击未设置的页面出现404,并记录日志:
点击消息,浏览器请求页面,服务端出错500,并记录日志:
发送私信,异步请求,服务端出错,返回JSON字符串,并记录日志: