当前位置:网站首页>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字符串,并记录日志:
边栏推荐
- Draw Your Cards
- 医疗影像领域AI软件开发流程
- The modification is not properly placed in the sandbox, causing Apple compatibility issues
- Detailed explanation of STP election (step + case)
- SQL注入 Less46(order by后的注入+rand()布尔盲注)
- There is a problem with the multiplayer-hlap package and the solution cannot be upgraded
- Pythagorean tuple od js
- Static routing + PAT + static NAT (explanation + experiment)
- FPGA-based vending machine
- Software Testing Defect Reporting - Definition, Composition, Defect Lifecycle, Defect Tracking Post-Production Process, Defect Tracking Process, Purpose of Defect Tracking, Defect Management Tools
猜你喜欢
【银行系列第一期】中国人民银行
SQL注入 Less46(order by后的注入+rand()布尔盲注)
ShardingJDBC使用总结
跨专业考研难度大?“上岸”成功率低?这份实用攻略请收下!
Tower of Hanoi problem
Static route analysis (the longest mask matching principle + active and standby routes)
字体压缩神器font-spider的使用
LeetCode 1161 The largest element in the layer and the LeetCode road of [BFS binary tree] HERODING
图解lower_bound&upper_bound
YOLOV5学习笔记(三)——网络模块详解
随机推荐
The modification is not properly placed in the sandbox, causing Apple compatibility issues
多线程下类对象的服务承诺探讨
Problems that need to be solved by the tcp framework
Face detection based on opencv
Live Preview | KDD2022 Doctoral Dissertation Award Champion and Runner-up Dialogue
First acquaintance with C language -- array
数学解决——环形链表问题
Teach you how to configure Jenkins automated email notifications
coldfusion8 background scheduled tasks take shell
AI在医疗影像设备全流程应用
MPPT solar charge controller data collection - through the gateway acquisition capacity battery SOC battery voltage, wi-fi
力扣刷题之有效的正方形(每日一题7/29)
ShardingJDBC usage summary
tcp框架需要解决的问题
The difference between link and @import
ShardingJDBC使用总结
Brute Force/Adjacency List Breadth First Directed Weighted Graph Undirected Weighted Graph
The Sad History of Image Processing Technology
YOLOV5学习笔记(二)——环境安装+运行+训练
Intel's software and hardware optimization empowers Neusoft to accelerate the arrival of the era of smart medical care