当前位置:网站首页>SSM integration exception handler and project exception handling scheme
SSM integration exception handler and project exception handling scheme
2022-07-02 16:20:00 【Xia Zhi 121】
Catalog
Two 、 Project exception handling scheme
Project exception classification
Project exception handling scheme
One 、 Exception handler
In the process of program development, it is inevitable to encounter abnormal phenomena
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 , Cause index exceptions, 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 )
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 , Each method is written separately , 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
@RestControllerAdvice
public class ProjectExceptionAdvice{
@ExceptionHandler(Exception.class)
public Result doException(Exception ex){
return new Result(666,null);
}
}name :@RestControllerAdvice
type : Class annotation
Location :Rest Style development controller enhancement class definition
effect : by Rest Enhance the controller class developed in style
Example :
@RestControllerAdvice public class ProjectExceptionAdvice{ }explain : This annotation comes with @ResponseBody Annotations and @Component annotation , Have corresponding functions
name :@ExceptionHandler
type : Method notes
Location : Controller method dedicated to 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
Example :
@RestControllerAdvice public class ProjectExceptionAdvice{ @ExceptionHandler(Exception.class) public Result doException(Exception ex){ return new Result(666,null); } }explain : Such methods can vary according to the exceptions handled , Make multiple methods to deal with the corresponding exceptions respectively
Exception handler processing effect comparison :
When there is no abnormality :

When there is abnormal :

Two 、 Project exception handling scheme
Project exception classification
Business exceptions (BusinessException)
Exceptions caused by standardized user behavior
Exceptions caused by irregular user behavior
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
Project exception handling
1、 Custom item exception system level exception
// Custom exception handler , Used to encapsulate exception information , Classify exceptions
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, String message) {
super(message);
this.code = code;
}
public SystemException(Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
}2、 Custom item business level exception
// Custom exception handler , Used to encapsulate exception information , Classify exceptions
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, String message) {
super(message);
this.code = code;
}
public BusinessException(Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
}3、 Custom exception code ( Keep adding )
public class Code {
public static final Integer SYSTEM_UNKNOW_ERROR = 50001;
public static final Integer SYSTEM_TIMEOUT_ERROR = 50002;
public static final Integer PROJECT_VALIDATE_ERROR = 60001;
public static final Integer PROJECT_BUSINESS_ERROR = 60002;
}4、 Trigger custom exception
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
public Book getById(Integer id) {
// Simulate business exceptions , Wrap as a custom exception
if(id < 0){
throw new BusinessException(Code.PROJECT_BUSINESS_ERROR," Do not operate illegally !");
}
return bookDao.getById(id);
}
}5、 Intercept and handle exceptions
//@RestControllerAdvice Used to identify that the current class is REST Exception handler corresponding to style
@RestControllerAdvice
public class ProjectExceptionAdvice {
//@ExceptionHandler Used to set the exception type corresponding to the current processor class
@ExceptionHandler(SystemException.class)
public Result doSystemException(SystemException ex){
// Log
// Send a message to O & M
// Send mail to developers ,ex Object to the developer
return new Result(ex.getCode(),null,ex.getMessage());
}
@ExceptionHandler(BusinessException.class)
public Result doBusinessException(BusinessException ex){
return new Result(ex.getCode(),null,ex.getMessage());
}
// In addition to custom exception handlers , Keep right Exception Exception handling of type , Used to handle unexpected exceptions
@ExceptionHandler(Exception.class)
public Result doOtherException(Exception ex){
// Log
// Send a message to O & M
// Send mail to developers ,ex Object to the developer
return new Result(Code.SYSTEM_UNKNOW_ERROR,null," The system is busy , Please contact the Administrator !");
}
}6、 Exception handler effect comparison


边栏推荐
- Text intelligent expansion and contraction control of swiftui text component (tutorial includes source code)
- 云原生的 CICD 框架:Tekton
- Aujourd'hui dans l'histoire: Alipay lance le paiement par code à barres; La naissance du père du système de partage du temps; La première publicité télévisée au monde...
- dried food! Understand the structural vulnerability of graph convolution networks
- 多数据源配置代码
- Kubernetes family container housekeeper pod online Q & A?
- 死锁的条件及解决方法
- idea jar包冲突排查
- [Xiaobai chat cloud] suggestions on container transformation of small and medium-sized enterprises
- Various entanglements between qvariant and Jason -- QT
猜你喜欢

【5G NR】RRC连接释放

Solve * * warning * *: your ApplicationContext is unlikely to start due to a @componentscan of the defau

Dimension table and fact table in data warehouse

How to use stustr function in Oracle view

Application of visualization technology in Nebula graph

MySQL min() finds the minimum value under certain conditions, and there are multiple results

Yyds dry inventory company stipulates that all interfaces use post requests. Why?

Mysql database mysqldump why there is no statement to create a database

Route service grid traffic through two-level gateway design

Vscode设置标签页多行显示
随机推荐
潘多拉 IOT 开发板学习(RT-Thread)—— 实验2 RGB LED 实验(学习笔记)
JS learning notes - variables
Song of cactus - throwing stones to ask the way (2)
Multi data source configuration code
Mathematical analysis_ Notes_ Chapter 6: Riemann integral of univariate function
MySQL min() finds the minimum value under certain conditions, and there are multiple results
Today in history: Alipay launched barcode payment; The father of time-sharing system was born; The first TV advertisement in the world
总结|机器视觉中三大坐标系及其相互关系
数学分析_笔记_第6章:一元函数的Riemann积分
Invalid bound statement (not found) solution summary
Set the background picture in the idea (ultra detailed)
Seal Library - installation and introduction
通过两级网关设计来路由服务网格流量
day4
Storage, reading and writing of blood relationship data of Nepal Graph & Data Warehouse
[Xiaobai chat cloud] suggestions on container transformation of small and medium-sized enterprises
Leetcode --- longest public prefix
2022最新最详细必成功的在Vscode中设置背景图、同时解决不受支持的问题
【5G NR】RRC连接释放
What are the necessary functions of short video app development?



