当前位置:网站首页>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字符串,并记录日志:
边栏推荐
- 真正的CTO,是一个懂产品的技术人
- 验证整数输入
- The principle of complete replication of virtual machines (cloud computing)
- There is a problem with the multiplayer-hlap package and the solution cannot be upgraded
- 经典链表OJ强训题——快慢双指针高效解法
- vlan间路由+静态路由+NAT(PAT+静态NAT)综合实验
- f.grid_sample
- CorelDRAW2022精简亚太新增功能详细介绍
- Problems that need to be solved by the tcp framework
- 公司官网建站笔记(六):域名进行公安备案并将备案号显示在网页底部
猜你喜欢

19. Support Vector Machines - Intuitive Understanding of Optimization Objectives and Large Spacing

General introduction to the Unity interface

How to do a startup CTO?

Face detection based on opencv

Fiddler captures packets to simulate weak network environment testing

Pythagorean tuple od js

The effective square of the test (one question of the day 7/29)

自动化办公案例:如何自动生成期数据?

局域网电脑硬件信息收集工具

leetcode-399: division evaluation
随机推荐
The Sad History of Image Processing Technology
【Bank Series Phase 1】People's Bank of China
PDF split/merge
AI在医疗影像设备全流程应用
mysql 索引
How to design the changing system requirements
Basic introduction to ShardingJDBC
Shell script to loop through values in log file to sum and calculate average, max and min
Can an inexperienced college graduate switch to software testing?my real case
STP选举(步骤+案列)详解
Software testing basic interface testing - getting started with Jmeter, you should pay attention to these things
Problems that need to be solved by the tcp framework
局域网电脑硬件信息收集工具
Basic learning about Redis related content
Classic linked list OJ strong training problem - fast and slow double pointer efficient solution
1. Non-type template parameters 2. Specialization of templates 3. Explanation of inheritance
cudaMemcpy study notes
print task sorting js od huawei
怎样做好一个创业公司CTO?
SQL注入 Less54(限制次数的SQL注入+union注入)