当前位置:网站首页>Item exception handling in SSM
Item exception handling in SSM
2022-07-28 20:07:00 【lwj_ 07】
One 、 Exception handler


reflection 1:

reflection 2:

Actually ,spring It has helped us solve the problem of handling exceptions early , No, we'll write it again AOP Code. , But we should follow spring Write in the format of handling exceptions
Simulate that the front end sends a request to access resources , Received an exception message ( At this time, there is no exception handler on the back end ):

After the front-end accesses the resource path of the added function , The information received is as follows :( At this time, the front end is confused , I TM Access is to add functions , this tm What's going back ~)

Therefore, we need to do exception handling at the back end ( Here are other exceptions , There is no need to create a class like system exceptions and business exceptions , Used to encapsulate prompt user information into attributes ):

After the backend handles the exception, the client accesses and adds functional resources again , What information will you receive :

Therefore, the client is also B Said , I didn't receive any data , What's the matter with me ,
Therefore, after the exception is handled by our backend , You can return some data to front-end users , Then the user will know , Oh, the back end is abnormal ~

The information received by the front-end user is as follows :

Two 、 How to deal with different kinds of exceptions in the project
Different types of abnormal forms in the project :

So how to deal with the above three types of exceptions :

The code demo is shown below :

First step : First, the system exception class 、 Write the business exception class :( In the actual development, there are only system exceptions in the business , Then write a system exception class , Here are three cases ( System exception 、 Business exceptions 、 Other exceptions are written ), In the actual development, the exception class is written according to the exception , Then you can process it through the exception handler and return the prompt message to the user )
System exception class :
package com.itheima.exception;
/**
* Business exception class
*
* notes : Inherit RuntimeException The purpose of the runtime exception class is to stop manually throwing up when an exception occurs at runtime , Automatically help us throw up
*
*/
public class SystemException extends RuntimeException{
private Integer code; // Add one code Number attributes , To mark what kind of exception appears in the future
/**
* It's best to write out the construction methods
*/
public SystemException(Integer code) {
this.code = code;
}
public SystemException(String message, Integer code) {
super(message);
this.code = code;
}
public SystemException(String message, Throwable cause, Integer code) {
super(message, cause);
this.code = code;
}
public SystemException(Throwable cause, Integer code) {
super(cause);
this.code = code;
}
public SystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Integer code) {
super(message, cause, enableSuppression, writableStackTrace);
this.code = code;
}
/**
* getter and setter Method
*/
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
Business exception class :
package com.itheima.exception;
/**
* System exception class
*
* notes : Inherit RuntimeException The purpose of the runtime exception class is to stop manually throwing up when an exception occurs at runtime , Automatically help us throw up
*
*/
public class BusinessException extends RuntimeException{
private Integer code; // Add one code Number attributes , Use the status code to mark what kind of exception appears in the future
/**
* It's best to write out the construction methods
*/
public BusinessException(Integer code) {
this.code = code;
}
public BusinessException(String message, Integer code) {
super(message);
this.code = code;
}
public BusinessException(String message, Throwable cause, Integer code) {
super(message, cause);
this.code = code;
}
public BusinessException(Throwable cause, Integer code) {
super(cause);
this.code = code;
}
public BusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Integer code) {
super(message, cause, enableSuppression, writableStackTrace);
this.code = code;
}
/**
* getter and setter Method
*/
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
The second step : Suppose the business side passes id There is a system exception when querying the function ( for instance : Server down ):
Then capture the system exceptions , Encapsulate the information you want to return to the front-end user into the attributes of the system exception class ( By construction method ), Then it returns the front-end user information through the exception handler
Be careful 1: Suppose that both system exceptions and business exceptions appear in a function of the business layer , So what kind of exception is caught first , The exception handler will get the exception information , And return the prompt data to the user ( Here are the system exceptions captured first , Because the system is abnormal, it ranks first )
package com.itheima.service.impl;
import com.itheima.controller.Code;
import com.itheima.dao.BookDao;
import com.itheima.domain.Book;
import com.itheima.exception.BusinessException;
import com.itheima.exception.SystemException;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookServiceImpl implements BookService {
/**
* Inject dao The data layer depends on : private BookDao bookDao;
* Then wait spring The container gets to the business layer of management BookServiceImpl After the object , And because there is a dependency between the business layer and the data layer
* Through the dependency relationship, you can call the function of adding, deleting, modifying and querying the data layer
*/
@Autowired // Automatic assembly ( Dealing with dependencies ) annotation
private BookDao bookDao;
// increase
public boolean save(Book book) {
// Call the added functions of the data layer
bookDao.save(book);
return true;
}
// Delete
public boolean delete(Integer id) {
// Call the deletion function of the data layer
bookDao.delete(id);
return true;
}
// Change
public boolean update(Book book) {
// Call the modification function of the data layer
bookDao.update(book);
return true;
}
// adopt id Inquire about
public Book getById(Integer id) {
/**
* The simulation assumes that this place appears System exception ( for instance : The server went down after the program ran here )
*
* We use it 1/0 To simulate the : Server down
*
*/
try {
int i =1/0; // The simulation system is abnormal
} catch (Exception e){ // After catching the system exception , Encapsulate the information you want to return to the front end into
// In the attribute of the system exception class ( By construction method )
throw new SystemException(" Server access timeout ~",e, Code.SYSTEM_ERR);
// Encapsulate the information you want to return to the front end into SystemException Object properties
// Code.SYSTEM_ERR : System abnormal status code identification 50001
}
/**
* Here the simulation hypothesis appears Business exceptions
*/
if (id==2){
throw new BusinessException(" Please don't challenge my patience with your technology ~",Code.BUSINESS_ERR);
// Code.BUSINESS_ERR : Business exception status code identification 60001
}
// Call the data layer to pass id Query function
Book books = bookDao.getById(id);
return books;
}
// Query all
public List<Book> getAll() {
// Call all functions of the data layer
List<Book> list = bookDao.getAll();
return list;
}
}
The third step : The system or business or other exception processing is carried out through the exception handler and encapsulated into the system exception class / The data returned to the customer in the business exception class attribute , Return to the user :
details : In real development , We can actually write these three exception handlers directly , Then, if there is a system exception in the project , Then it is directly handled by the system exception handler and returned to the user information , If it is the other two , It can also be directly caught by the other two exception handlers and then handle exceptions
package com.itheima.controller;
import com.itheima.exception.BusinessException;
import com.itheima.exception.SystemException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* spring Handling exceptions ( Exception handler class )
*/
// @ControllerAdvice // This is a common style annotation for handling exceptions ( As long as the access path is not REST Use this annotation for style )
@RestControllerAdvice // This is a REST Style annotation for handling exceptions ( tell spring This is an annotation of a class that handles exceptions )
// notes 1: This @RestControllerAdvice Annotations need to be SpringMvcConfig Class @ComponentScan({"com.itheima.controller"}) annotation
// Scan to ,(SpringMvcConfig The scanning annotation of the class just reaches controller It's a bag , So you can scan , So if you change to another bag , Remember to sweep )
public class ProjectExceptionAdvice {
/**
* notes : System exception handler
*
* @return: Return to the front-end information
*/
@ExceptionHandler(SystemException.class) // The function of this annotation : Whether the interception is a system exception , If yes, call the following methods to handle exceptions
public Result doSystemException(SystemException sy){
// (SystemException sy): hold SystemException Object passed ( Because when the business layer simulated the system exception just now , Encapsulate the information returned to the front end into sy Object attribute )
/**
* After getting the system exception, you need to do the following steps :
* 1、 Log
* 2、 Send it to O & M , Developer
* 3、 Appease the customer ( There is an exception when the customer accesses resources , We must say something nice to users )
*/
return new Result(null,sy.getCode(), sy.getMessage());
// Encapsulate into sy The system exception status code information in the system exception class attribute is returned to the user
}
/**
* notes : Business exception handler ( It is the same as the system exception handler )
*
* @return: Return to the front-end information
*/
@ExceptionHandler(BusinessException.class) // Whether the interception is a business exception , If yes, call the following methods to handle exceptions
public Result doBusinessException(BusinessException bs){
return new Result(null,bs.getCode(),bs.getMessage());
}
/**
* notes : Other exception handlers ( It can be understood as all exceptions except business exceptions and system exceptions )
*/
@ExceptionHandler(Exception.class) // Whether the interception is other exception , If yes, call the following methods to handle exceptions
public Result doException(){
return new Result(null,0," Something is abnormal, iron ~");
}
}
Suppose the client accesses the system abnormally id When querying the function :

repair :Code class : Dedicated to storing success / Failure identifier
package com.itheima.controller;
/**
* Analyze the role of this class :
* Mark the status code ( such as 1: It means success ,2: It means failure ) Class ,( Result Inside )
*
* Be careful : These status codes are not fixed , It is a kind of state information that the front-end programmer and the back-end programmer discuss and stipulate in the actual development ,
* Through these negotiated status codes , You can know whether you get the data
*
*/
public class Code {
/**
* The status code mark of the success of calling the function of adding, deleting, modifying and checking
*
* notes : the reason being that static Statically decorated , So you can directly use the class name Code Call property name
* public modification : On behalf of the public ( in other words , Under any package, just pass the class name . Can be accessed in any way Code Attribute value under class )
*
*/
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 SELECT_OK = 20041;
/**
* The status code mark of the failure to call the function of adding, deleting, modifying and querying
*/
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 SELECT_ERR = 20040;
/**
* System exception & The business is exceptionally successful / Failure status code mark
*/
public static final Integer SYSTEM_ERR =50001; // The system abnormal status code appears
public static final Integer BUSINESS_ERR =60001; // Business exception status code appears
}
边栏推荐
- 利用STM32的HAL库驱动1.54寸 TFT屏(240*240 ST7789V)
- [网络]跨区域网络的通信学习路由表的工作原理
- 数字滤波器设计——Matlab
- How navicate modifies the database name
- C+ + core programming
- Leetcode day4 the highest paid employee in the Department
- Basic knowledge of communication network 01
- English translation Portuguese - batch English conversion Portuguese - free translation and conversion of various languages
- JS batch add event listening onclick this event delegate target currenttarget onmouseenter OnMouseOver
- leetcode day1 分数排名
猜你喜欢
![[C language] print pattern summary](/img/48/d8ff17453e810fcd9269f56eda4d47.png)
[C language] print pattern summary
![[C language] advanced pointer exercise 1](/img/ee/c62919330edb4a0b5a2a4b027e5b5c.png)
[C language] advanced pointer exercise 1

Handan, Hebei: expand grassroots employment space and help college graduates obtain employment

KPMG China: insights into information technology audit projects of securities fund management institutions

String中常用的API
![[NPP installation plug-in]](/img/6f/97e53116ec4ebc6a6338d125ddad8b.png)
[NPP installation plug-in]

个人博克系统登录点击图形验证码的集成与实现

5. Difference between break and continue (easy to understand version)

zfoo增加类似于mydog的路由

How many types of rain do you know?
随机推荐
Why is there no log output in the telnet login interface?
私有化部署的即时通讯平台,为企业移动业务安全保驾护航
[NPP installation plug-in]
认识中小型局域网WLAN
Hebei: stabilizing grain and expanding beans to help grain and oil production improve quality and efficiency
[C language] Hanoi Tower problem [recursion]
Special draft of Mir | common sense knowledge and reasoning: representation, acquisition and application (deadline on October 31)
Sequential linear table - practice in class
11. Learn MySQL union operator
通信网络基础知识01
String中常用的API
mmo及时战斗游戏中的场景线程分配
[wechat applet development] page navigation and parameter transmission
[C language] print pattern summary
个人博克系统登录点击图形验证码的集成与实现
English translation Arabic - batch English translation Arabic tools free of charge
2022年下半年系统集成项目管理工程师认证8月20日开班
Labelme (I)
[C language] Fibonacci sequence [recursion and iteration]
克服“看牙恐惧”,我们用技术改变行业