当前位置:网站首页>8. Unified exception handling (controller notifies @ControllerAdvice global configuration class, @ExceptionHandler handles exceptions uniformly)
8. Unified exception handling (controller notifies @ControllerAdvice global configuration class, @ExceptionHandler handles exceptions uniformly)
2022-07-31 02:39:00 【一个偷笑】
- SpringBoot设计,如果出现错误404或500,Automatically call under a specific pathhtml页面(Paths and names are specific)./templates/error/404.html、/templates/error/500.html.This page is automatically called when there is an error in the program.
- But the error has async request error,Also want to log at the same time.Then use the unified processing method,即全局配置.使用HomeController,Add a request to get the error page,手动重定向路径.
@RequestMapping(path = "/error", method = RequestMethod.GET)
public String getErrorPage() {
return "/error/500";
}
在Controller下新建adviceNotification configuration package,新建ExceptionAdvice.用到两个注解:@ControllerAdvice,@ExceptionHandler.
- 是Controller全局配置类,Not to anyControllerdo the configuration again,can be done uniformlyController的全局配置.@ControllerAdvice用来修饰类.
- 异常处理方案**@ExceptionHandler**、绑定数据方案**@ModelAttribute**、绑定参数方案**@DataBinder**. They are both used to decorate methods.
- 这里只演示,统一处理异常(@ExceptionHandler)
// 是Controller全局配置类,Not to anyControllerdo the configuration again,can be done uniformlyController的全局配置[email protected]用来修饰类.
// 异常处理方案@ExceptionHandler、绑定数据方案@ModelAttribute、绑定参数方案@DataBinder. They are both used to decorate methods.
// 这里只演示,统一处理异常(@ExceptionHandler)
@ControllerAdvice(annotations = Controller.class) // 限定注解@Controller,Otherwise the component scans allbean
public class ExceptionAdvice {
private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
@ExceptionHandler({
Exception.class})// 处理哪些异常?Exception是所有异常的父类,All exceptions are handled
// 有异常controllerwill passException
public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
// 记录日志
logger.error("服务器发生异常:" + e.getMessage());//Unusual summary
for (StackTraceElement element : e.getStackTrace()) {
//Record the information of all stacks of exceptions
logger.error(element.toString());
}
// 给浏览器响应
// Depends what the request is,Want the server to return the web pagehtml/异步请求JSON(xml).Get it from the request header.
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");
}
}
}
Click on the Unconfigured page to appear404,并记录日志:
点击消息,浏览器请求页面,服务端出错500,并记录日志:
发送私信,异步请求,服务端出错,返回JSON字符串,并记录日志:
边栏推荐
- Android's webview cache related knowledge collection
- mysql 索引
- 1. Non-type template parameters 2. Specialization of templates 3. Explanation of inheritance
- AtCoder Beginner Contest 261 Partial Solution
- 汉源高科8路HDMI综合多业务高清视频光端机8路HDMI视频+8路双向音频+8路485数据+8路E1+32路电话+4路千兆物理隔离网络
- 全流程调度——MySQL与Sqoop
- Word/Excel fixed table size, when filling in the content, the table does not change with the cell content
- 你们程序员为什么不靠自己的项目谋生?而必须为其他人打工?
- MPPT太阳能充放电控制器数据采集-通过网关采集电池电压容量电量SOC,wifi传输
- LeetCode Daily Question 2022/7/25-2022/7/31
猜你喜欢
Pythagorean tuple od js
The comprehensive result of the case statement, do you know it?[Verilog Advanced Tutorial]
7、私信列表
FPGA-based vending machine
Face detection based on opencv
Drools Rule Properties, Advanced Syntax
There is a problem with the multiplayer-hlap package and the solution cannot be upgraded
f.grid_sample
自动化办公案例:如何自动生成期数据?
Drools basic introduction, introductory case, basic syntax
随机推荐
Observer mode (1)
16、热帖排行
完整复制虚拟机原理(云计算)
MPPT solar charge controller data collection - through the gateway acquisition capacity battery SOC battery voltage, wi-fi
Tower of Hanoi problem
Software testing basic interface testing - getting started with Jmeter, you should pay attention to these things
[1153]mysql中between的边界范围
修改未正确放入沙盒造成苹果兼容性问题
工程(五)——小目标检测tph-yolov5
数学解决——环形链表问题
CentOS7下mysql5.7.37的卸载【完美方案】
To write good test cases, you must first learn test design
STM32CUBEMX develops GD32F303 (11) ---- ADC scans multiple channels in DMA mode
f.grid_sample
Draw Your Cards
Basic learning about Redis related content
YOLOV5学习笔记(三)——网络模块详解
cudaMemcpy study notes
19. Support Vector Machines - Intuitive Understanding of Optimization Objectives and Large Spacing
如何搭建私有yum源