当前位置:网站首页>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字符串,并记录日志:
边栏推荐
猜你喜欢

CentOS7下mysql5.7.37的安装【完美方案】

图像处理技术的心酸史

What level of software testing does it take to get a 9K job?

f.grid_sample

Live Preview | KDD2022 Doctoral Dissertation Award Champion and Runner-up Dialogue

Force buckled brush the stairs (7/30)

Hanyuan Hi-Tech 8-channel HDMI integrated multi-service high-definition video optical transceiver 8-channel HDMI video + 8-channel two-way audio + 8-channel 485 data + 8-channel E1 + 32-channel teleph

Real-time image acquisition based on FPGA

JS 函数 this上下文 运行时点语法 圆括号 数组 IIFE 定时器 延时器 self.备份上下文 call apply

Inter-vlan routing + static routing + NAT (PAT + static NAT) comprehensive experiment
随机推荐
Brute Force/Adjacency List Breadth First Directed Weighted Graph Undirected Weighted Graph
String为什么不可变?
系统需求多变如何设计
Discourse 自定义头部链接(Custom Header Links)
CentOS7下mysql5.7.37的卸载【完美方案】
multiplayer-hlap 包有问题,无法升级的解决方案
Draw Your Cards
16. Registration Center-consul
12 磁盘相关命令
YOLOV5学习笔记(三)——网络模块详解
AtCoder Beginner Contest 261 部分题解
Installation, start and stop of redis7 under Linux
怎样做好一个创业公司CTO?
【CV项目调试】CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT问题
ShardingJDBC usage summary
自动化办公案例:如何自动生成期数据?
软件积累 -- 截图软件ScreenToGif
Basic learning about Redis related content
Unity3D Button 鼠标悬浮进入与鼠标悬浮退出按钮事件
Classic linked list OJ strong training problem - fast and slow double pointer efficient solution