当前位置:网站首页>[ssm] exception handling
[ssm] exception handling
2022-07-23 09:38:00 【18-year-old hates programming】
List of articles
Exception handler
Problem introduction
modify BookController Class getById Method
@GetMapping("/{id}")
public Result getById(@PathVariable Integer id) {
// Manually add an error message
if(id==1){
int i = 1/0;
}
Book book = bookService.getById(id);
Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
String msg = book != null ? "" : " Data query failed , Please try again !";
return new Result(code,book,msg);
}
Restart the running project , Use PostMan Send a request , When incoming id by 1, The following effects will appear :

The format of this message received by the front end is inconsistent with that agreed by us , How to solve this problem ?
Before solving the problem , Let's first look at the types of anomalies and the reasons for them :
- 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 )
After reading the above abnormal positions , You'll find that , Exceptions can occur anywhere we develop , And these exceptions cannot be avoided . So we have to deal with exceptions .
reflection
Exceptions occur at all levels , Which layer is the exception handling code written on ?
All exceptions are thrown to the presentation layer for processing
There are many kinds of exceptions , How does the presentation layer handle all exceptions to ?
Anomaly classification
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
For the above problems and solutions ,SpringMVC Has provided us with a set of solutions :
Exception handler :
Centralized 、 Handle exceptions in the project in a unified way .

Use of exception handlers
The structure of the project is still based on our previous :
We usually put this exception handler in the presentation layer . After creation, we should first declare that this class is used for exception handling :
- @ControllerAdvice
- @RestControllerAdvice
Because we are now using REST Style , So we use the second .
Then we write a method in this class to handle exceptions , And annotate @ExceptionHandler To explain which type of exception you want to handle :
//@RestControllerAdvice Used to identify that the current class is REST Exception handler corresponding to style
@RestControllerAdvice
public class ProjectExceptionAdvice {
// In addition to custom exception handlers , Keep right Exception Exception handling of type , Used to handle unexpected exceptions
@ExceptionHandler(Exception.class)
public void doException(Exception ex){
System.out.println(" An exception occurred here ")
}
}
Be careful :
This class of exception handlers belongs to the presentation layer , And it must be SpringMvcConfig To scan to , Otherwise it doesn't work .
We can casually modify the method of a presentation layer so that it can throw exceptions , Then we will visit , The console will show :
An exception occurred here
But there is nothing in the front end :
Next, we use the exception handler class to return the result to the front end :
//@RestControllerAdvice Used to identify that the current class is REST Exception handler corresponding to style
@RestControllerAdvice
public class ProjectExceptionAdvice {
// In addition to custom exception handlers , Keep right Exception Exception handling of type , Used to handle unexpected exceptions
@ExceptionHandler(Exception.class)
public Result doException(Exception ex){
System.out.println(" Hey , Where do you run !")
return new Result(666,null," Hey , Where do you run !");
}
}
Start the running program , test :
thus , Even if an exception is thrown during background execution , Finally, it can be returned to the front end according to the format agreed between us and the front end .
summary
Knowledge point 1:@RestControllerAdvice
| name | @RestControllerAdvice |
|---|---|
| type | Class annotation |
| Location | Rest Style development controller enhancement class definition |
| effect | by Rest Enhance the controller class developed in style |
explain : This annotation comes with @ResponseBody Annotations and @Component annotation , Have corresponding functions

Knowledge point 2:@ExceptionHandler
| 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 |
explain : Such methods can vary according to the exceptions handled , Make multiple methods to deal with the corresponding exceptions respectively
Project exception handling
Exception handlers we can already use , So how to deal with exceptions in our project ?
Because there are many kinds of exceptions , If every exception corresponds to one @ExceptionHandler, How many methods do you have to write to handle their own exceptions , So before we deal with exceptions , Need a classification of exceptions :
Business exceptions (BusinessException)
Exceptions caused by standardized user behavior
The user did not fill in the data according to the specified format when entering the content on the page , If you enter a string in the age box

Exceptions caused by nonstandard user behavior operations
If the user intentionally transmits wrong data

System exception (SystemException)
- Predictable but unavoidable exceptions during project operation
- Such as database or server downtime
- Predictable but unavoidable exceptions during project operation
Other anomalies (Exception)
Unexpected exceptions by programmers , Such as : The file used does not exist

After classifying the exceptions , For different types of exceptions , To provide specific solutions :
Exception resolution
- Business exceptions (BusinessException)
- Send the corresponding message to the user , Remind the standard operation
- It is common to prompt that the user name already exists or the password format is incorrect, etc
- Send the corresponding message to the user , Remind the standard operation
- System exception (SystemException)
- Send a fixed message to the user , Appease users
- The system is busy , Please try again later
- The system is being maintained and upgraded , Please try again later
- There's something wrong with the system , Please contact the system administrator
- Send specific messages to O & M personnel , Remind maintenance
- You can send text messages 、 Email or company intercom Software
- Log
- Sending messages and logging are invisible to users , It belongs to the background program
- Send a fixed message to the user , Appease users
- Other anomalies (Exception)
- Send a fixed message to the user , Appease users
- Send specific messages to programmers , Remind maintenance ( Within the expected range )
- Generally, the procedure does not consider all , For example, non null verification is not done
- Log
Specific implementation of exception solution
Ideas :
First, through the custom exception , complete BusinessException and SystemException The definition of
Wrap other exceptions into custom exception types
Handle different exceptions in the exception handler class
step 1: Custom exception classes
We can create a separate folder , Specially put our custom exceptions ;
// 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;
}
}
// 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;
}
}
explain :
- Let the custom exception class inherit
RuntimeExceptionAre the benefits of , Later, when throwing these two exceptions , You don't have to be in try…catch… or throws 了 - Add... To the custom exception class
codeThe reason of attribute is to better distinguish which business the exception comes from
step 2: Package other exceptions into custom exceptions
If be in, BookServiceImpl Of getById Method throw exception , How to pack it ?
public Book getById(Integer id) {
// Simulate business exceptions , Wrap as a custom exception
if(id == 1){
throw new BusinessException(Code.BUSINESS_ERR," Please don't use your technology to challenge my patience !");
}
// The simulation system is abnormal , Package possible exceptions , Convert to custom exception
try{
int i = 1/0;
}catch (Exception e){
throw new SystemException(Code.SYSTEM_TIMEOUT_ERR," Server access timeout , Please try again !",e);
}
return bookDao.getById(id);
}
The specific packaging methods are :
- Mode one :
try{}catch(){}stay catch In a new way throw We can customize exceptions . - Mode two : direct throw You can customize the exception
Above in order to make code Look more professional , We are Code Add the required attributes in the class
// Status code
public class Code {
public static final Integer SAVE_OK = 20011;
public static final Integer DELETE_OK = 20021;
public static final Integer UPDATE_OK = 20031;
public static final Integer GET_OK = 20041;
public static final Integer SAVE_ERR = 20010;
public static final Integer DELETE_ERR = 20020;
public static final Integer UPDATE_ERR = 20030;
public static final Integer GET_ERR = 20040;
public static final Integer SYSTEM_ERR = 50001;
public static final Integer SYSTEM_TIMEOUT_ERR = 50002;
public static final Integer SYSTEM_UNKNOW_ERR = 59999;
public static final Integer BUSINESS_ERR = 60002;
}
step 3: Handle custom exceptions in the processor class
//@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_ERR,null," The system is busy , Please try again later !");
}
}
Now let's run the project , Then visit our resources :
according to ID Inquire about ,
If the parameter passed in is 1, Will be submitted to the BusinessException:
If other parameters are passed in , Will be submitted to the SystemException:
For exceptions, we have already handled them , No matter which layer throws an exception in the background , Will be returned in the way we have agreed with the front end , The front end only needs to get the information to , Show different contents according to whether the return is correct or not .
summary
The exception handling method in future projects is :
边栏推荐
- La fosse Piétinée par l'homme vous dit d'éviter les 10 erreurs courantes dans les tests automatisés
- 【Jailhouse 文章】Virtualization over Multiprocessor System-on-Chip an Enabling Paradigm for...
- Solution of equipment inspection in sewage treatment plant
- LEADTOOLS 20-22 Crack-DotNetCore!!!
- 2022.7.22-----leetcode.757
- Accumulation of FPGA errors
- IBM:到2030年实现容错量子优势
- operator=中自我赋值和异常安全问题
- General design of SQL user table
- Installation, configuration and use of sentry
猜你喜欢

Wallys/DR4019S/IPQ4019/11ABGN/802.11AC/high power

VirtualBox NAT network mode configuration

涨薪神器

Déterminer s'il s'agit d'un type vide

The pit trodden by real people tells you to avoid the 10 mistakes often made in automated testing
![[SSM]异常处理](/img/bb/2669d2a3ee725aa4ab8443aed0a8be.png)
[SSM]异常处理

真人踩过的坑,告诉你避免自动化测试常犯的10个错误

EasyV半年度“官方网站热门内容”排行榜盘点

给我五分钟,给你一片“云”
![[MySQL from introduction to proficiency] [advanced chapter] (VII) design an index scheme in index & InnoDB](/img/1f/a923a5245daa82771321a82fa5dc90.png)
[MySQL from introduction to proficiency] [advanced chapter] (VII) design an index scheme in index & InnoDB
随机推荐
一文搞定C语言指针
canal 配置01
canal 第五篇
What is the combined effect of compose and recyclerview?
Can GF futures open an account? Is it safe?
污水处理厂设备巡检的解决方案
opensmile简介和安装过程中遇到的问题记录
免费屏幕录像机
Developers must see | devweekly issue 1: what is time complexity?
Selenium.webdriver gets the result and converts it to JSON format
PNA肽核酸修饰多肽Pro-Phe-Arg-pNA (S-2302)|Dnp-Gly-X-L-Pro-Gly-pNA
Tidb 3.0安装
QT显示中文乱码
codeforces每日5题(均1500)-第二十三天
mysql的key和index的区别及创建删除索引
【HLS】流水线仿真之排队函数的调用
动态设置小程序的navigationBarTitleText
Pytorch visualization
Double disk: what is a b+ tree? Do you know how b+ trees build ordered tables? What are the characteristics of b+ tree
以低代码软件构建物联网基础设施建设