当前位置:网站首页>SSM integration - exception handler and project exception handling scheme
SSM integration - exception handler and project exception handling scheme
2022-07-26 18:41:00 【Jianghu great Xia Ye Huahua】
- Exceptions are inevitable in the process of program development
- The common locations and causes of abnormal phenomena are as follows :
- Exceptions thrown inside the framework : Caused by non-conforming use
- Exceptions thrown by the data layer : Due to external server failure ( for example : Server access timeout )
- Exceptions thrown by the business layer : Due to business logic writing errors ( for example : Traverse business writing operations , Lead to cable bow | Abnormal etc. )
- Exceptions thrown by the presentation layer : Due to data collection 、 Verification and other rules lead to ( for example : Mismatched data types cause exceptions )
- Exception thrown by tool class : Because the writing of tool books is not rigorous and robust enough, it leads to ( for example : The connection that needs to be released has not been released for a long time, etc )
problem :
1、 Exceptions occur at all levels , Which layer is the exception handling code written on ??
All exceptions are thrown to the presentation layer for processing
2、 The presentation layer handles exceptions , Write separately in each method , The amount of code written is huge and the meaning is not strong , How to solve ??
AOP thought
Exception handler
Centralized 、 Handle exceptions in the project in a unified way

1、 Using annotations @RestControllerAdvice Declare this class as an exception handler class
This annotation comes with @ResponseBody Annotations and @Component annotation , Have corresponding functions
/**
* Exception handler
*/
@RestControllerAdvice
public class ProjectExceptionAdvice {
@ExceptionHandler(Exception.class)
public Result doException(Exception ex){
var msg = " abnormal , Here you are !";
System.out.println(msg);
return new Result(msg,400,ex.getMessage());
}
}
2、 Using annotations @ExceptionHandler , Above the controller method used to define exception handling
effect : Set the handling scheme of the specified exception , The function is equivalent to the controller method , Terminate the execution of the original controller after an exception occurs , And go to the current method to execute
Such methods can vary according to the exceptions handled , Make multiple methods to deal with the corresponding exceptions respectively .
effect :

Project exception handling scheme
Project exception classification
- Business exceptions (BusinessException)
- Exceptions caused by standardized user behavior
- Exceptions caused by nonstandard user behavior operations
- System exception (SystemException)
- Predictable and unavoidable exceptions during project operation
- Other anomalies (Exception)
- Unexpected exceptions by programmers
Project exception handling scheme
- Business exceptions (BusinessException)
- Send the corresponding message to the user , Remind the standard operation
- System exception (SystemException)
- Send a fixed message to the user , Appease users
- Send specific messages to O & M personnel , Remind maintenance
- Log
- Other anomalies (Exception)
- Send a fixed message to the user , Appease users
- Send specific messages to programmers , Remind maintenance ( Within the expected range )
- Log
1、 Custom item system level exception
public class SystemException extends RuntimeException{
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public SystemException(Integer code) {
this.code = code;
}
public SystemException(String message, Throwable cause) {
super(message, cause);
}
public SystemException(String message, Throwable cause, Integer code) {
super(message, cause);
this.code = code;
}
public SystemException(String message, Integer code) {
super(message);
this.code = code;
}
}2、 Custom item business level exception
public class BusinessException extends RuntimeException {
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public BusinessException(Integer code) {
this.code = code;
}
public BusinessException(String message, Throwable cause, Integer code) {
super(message, cause);
this.code = code;
}
public BusinessException(String message, Integer code) {
super(message);
this.code = code;
}
}3、 Custom exception code
public class Code {
......
// Unknown error
public static final Integer SYSTEM_UNKNOW_ERR=40010;
// Timeout error
public static final Integer SYSTEM_TIMEOUT_ERR=40020;
public static final Integer PROJECT_VALIDATE_ERR=40020;
public static final Integer PROJECT_BUSINESS_ERR=40020;
}4、 Trigger custom exception
@GetMapping("/{id}")
public Result findById(@PathVariable int id) {
if (id < 0) {
throw new BusinessException(" Do not operate illegally !", Code.PROJECT_BUSINESS_ERR);
}
var data = userService.findById(id);
boolean flag = false;
if (data != null) {
flag = true;
}
var code = flag ? Code.GET_OK : Code.GET_ERR;
var msg = flag ? " Data query successful " : " Data query failed ";
Result result = new Result(data, code, msg);
return result;
}5、 Intercept and handle exceptions
/**
* Exception handler
*/
@RestControllerAdvice
public class ProjectExceptionAdvice {
@ExceptionHandler(BusinessException.class)
public Result doBusinessException(BusinessException ex){
return new Result(ex.getMessage(),ex.getCode(),ex.getMessage());
}
@ExceptionHandler(SystemException.class)
public Result doSystemException(SystemException ex){
// Log ( The error stack )todo
// Send mail to developers todo
// Send SMS to operation and maintenance personnel todo
return new Result(ex.getMessage(),ex.getCode(),ex.getMessage());
}
@ExceptionHandler(Exception.class)
public Result doException(Exception ex){
// Log ( The error stack )todo
// Send mail to developers todo
// Send SMS to operation and maintenance personnel todo
var msg = " The system is busy , Please contact the Administrator !";
return new Result(msg,Code.SYSTEM_UNKNOW_ERR,ex.getMessage());
}
}6、 Exception handler effect comparison


边栏推荐
- LeetCode_134_加油站
- 更安全、更健康、无续航焦虑,魏牌拿铁DHT-PHEV来了
- 任正非首度揭秘:华为差点100亿美元“卖身”摩托罗拉背后的故事!
- Test cases of common functions
- 立即报名 | 云原生技术交流 Meetup 广州站已开启,8 月 6 号与你相遇!
- 分布式链路追踪Jaeger在Golang中的使用
- Redis主从复制,读写分离,哨兵模式
- Ministry of Finance: IC design enterprises and software enterprises will be exempted from corporate income tax this year and next!
- 455. 分发饼干【双指针 ++i、++j】
- 自动化测试工具-Playwright(快速上手)
猜你喜欢

ALV屏幕输入选项学习

SSM practice day 5

Meta Cambria手柄曝光,主动追踪+多触觉回馈方案

Linked list - the first common node of two linked lists

NFT数字藏品系统开发:同道大叔首推祈福系列数字藏品开售即罄

Linked list - the penultimate K nodes

Baidu PaddlePaddle easydl x wesken: see how to install the "eye of AI" in bearing quality inspection

Offer set (1)

PS_1_认识主界面_新建文档(分辨率)_打开保存(序列动画)

Visual VM positioning oom, fullgc usage
随机推荐
Are you suitable for automated testing?
The step jumping expansion problem of sword finger offer
J9数字论:如何避免踩雷多头陷阱?
Sword finger offer regular expression matching
链表-合并两个排序的列表
数据库索引的原理,为什么要用 B+树,为什么不用二叉树?
文件上传下载测试点
Neural network learning (2) introduction 2
同步时现实密码不匹配
14. Gradient detection, random initialization, neural network Summary
Linked list - reverse linked list
如何做好测试用例设计
Lombok常用注解
Continue to work hard on your skills, and the more you learn, the more you will learn
Visual VM positioning oom, fullgc usage
Pyqt5 rapid development and practice 3.5 menu bar and toolbar
Leetcode 50 day question brushing plan (day 3 - concatenate substrings of all words 10.00-13.20)
Summary of some problems encountered in developing WinForm (continuous updating)
LeetCode_1005_K次取反后最大化的数组和
Linked list - the first common node of two linked lists