1.应用
可以统一帮助处理一些异常(出现错误之后,跳转到我们制作好的错误页面),主要针对于表现层进行实现
2.springboot实现

只要是这种目录结构,只要出错就会直接进行跳转
虽然非常方便,但是如果我们要记录日志,还是要用spring提供的处理机制
3.各种注解
- @ControllerAdvice 用于修饰类,表示该类是Controller的全局配置类
在此类中,可以对Controller进行如下的三种全局配置 异常处理方案、绑定数据方案、绑定参数方案 - @ExceptionHandler 用于修饰方法,该方法会在Controller出现异常后被调用
- @ModelAttribute 用于修饰方法, 该方法会在Controller方法执行前被调用,用于为Model对象绑定参数
- @DataBinder 用于修饰方法,该方法会在Controller执行前被调用,用于绑定参数的转换器
4.案例
编写通知类,这样无论哪个Controller出现了问题都会这么处理
@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {
private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
@ExceptionHandler((Exception.class))
public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
logger.error("服务器发生异常:" + e.getMessage());
for(StackTraceElement element : e.getStackTrace()){
logger.error(element.toString());
}
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, "服务器发生异常!"));
}else{
response.sendRedirect(request.getContextPath() + "/error");
}
}
}
本文介绍了如何使用SpringBoot实现全局异常处理,通过@ControllerAdvice和@ExceptionHandler注解来捕获并处理Controller层的异常,同时结合日志记录确保错误信息的留存。在处理异常时,不仅会跳转到错误页面,对于Ajax请求则返回JSON错误信息。此外,还展示了如何结合HttpServletRequest和HttpServletResponse进行响应处理。
17万+

被折叠的 条评论
为什么被折叠?



