当前位置:网站首页>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


边栏推荐
- Maui学习之路(三)--Winui3深入探讨
- 构建多架构镜像的最佳实践
- What is Amazon keyword index? The consequences of not indexing are serious
- (practice C language every day) the sum of the nearest three numbers
- JS learning notes - variables
- Group by的用法
- 死锁的条件及解决方法
- Processing gzip: stdin: not in gzip format: child returned status 1tar: error is not recoverable: exitin
- Does bone conduction earphone have external sound? Advantages of bone conduction earphones
- Pandora IOT development board learning (RT thread) - Experiment 2 RGB LED experiment (learning notes)
猜你喜欢

触发器:Mysql实现一张表添加或删除一条数据,另一张表同时添加

Text intelligent expansion and contraction control of swiftui text component (tutorial includes source code)

Another graduation season

Construction and business practice of Zhongke brain knowledge map platform

Traversal before, during and after binary tree

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

Remove the underline in router link

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

SSM整合-异常处理器及项目异常处理方案

Mathematical analysis_ Notes_ Chapter 6: Riemann integral of univariate function
随机推荐
Seal Library - installation and introduction
win10系统升级一段时间后,内存占用过高
Sqlserver queries which indexes are underutilized
Practice of traffic recording and playback in vivo
Multi data source configuration code
月报总结|Moonbeam6月份大事一览
AWS virtual machine expansion
Various entanglements between qvariant and Jason -- QT
Add user-defined formula (time sharing t+0) to mobile app access as an example
PyC file decompile
做机器视觉哪个软件好?
手机app通达信添加自定义公式(分时T+0)为例子讲解
Foreign enterprise executives, continuous entrepreneurs, yoga and skiing masters, and a program life of continuous iteration and reconstruction
Data Lake (11): Iceberg table data organization and query
源码look me
华为云服务器安装mysqlb for mysqld.service failed because the control process exited with error code.See “sys
2020.4.12 byte written test questions B DP D monotone stack
Boot 连接 Impala数据库
Flink real-time data warehouse (IX): incremental synchronization of data in MySQL
The sea of stars hidden behind the nebula graph


