当前位置:网站首页>8、统一处理异常(控制器通知@ControllerAdvice全局配置类、@ExceptionHandler统一处理异常)
8、统一处理异常(控制器通知@ControllerAdvice全局配置类、@ExceptionHandler统一处理异常)
2022-07-31 02:36:00 【A snicker】
- 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字符串,并记录日志:
边栏推荐
- 修改未正确放入沙盒造成苹果兼容性问题
- Validate XML documents
- 1. Non-type template parameters 2. Specialization of templates 3. Explanation of inheritance
- Mathematics to solve the problem - circular linked list
- 局域网电脑硬件信息收集工具
- Between two orderly array of additive and Topk problem
- The effective square of the test (one question of the day 7/29)
- 全流程调度——MySQL与Sqoop
- cudaMemcpy学习笔记
- String为什么不可变?
猜你喜欢
局域网电脑硬件信息收集工具
Static routing + PAT + static NAT (explanation + experiment)
Detailed explanation of STP election (step + case)
leetcode-399: division evaluation
Installation, start and stop of redis7 under Linux
二层广播风暴(产生原因+判断+解决)
f.grid_sample
Introduction and use of Drools WorkBench
mmdetection训练一个模型相关命令
The application of AI in the whole process of medical imaging equipment
随机推荐
Can an inexperienced college graduate switch to software testing?my real case
print task sorting js od huawei
【Bank Series Phase 1】People's Bank of China
f.grid_sample
The difference between link and @import
golang GUI for nuxui — HelloWorld
Brute Force/Adjacency Matrix Breadth First Directed Weighted Graph Undirected Weighted Graph
cudaMemcpy study notes
你们程序员为什么不靠自己的项目谋生?而必须为其他人打工?
曼城推出可检测情绪的智能围巾,把球迷给整迷惑了
AI在医疗影像设备全流程应用
Intel's software and hardware optimization empowers Neusoft to accelerate the arrival of the era of smart medical care
f.grid_sample
系统需求多变如何设计
基于FPGA的售货机
BAT卖不动「医疗云」:医院逃离、山头林立、行有行规
SQL注入 Less54(限制次数的SQL注入+union注入)
Introduction to flask series 】 【 flask - using SQLAlchemy
19.支持向量机-优化目标和大间距直观理解
Draw Your Cards