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


边栏推荐
- 财政部:今明两年对集成电路设计企业和软件企业免征企业所得税!
- 【在 Kotlin 中添加条件行为】
- Leetcode 0137. number II that appears only once
- LeetCode_1005_K次取反后最大化的数组和
- 成为测试/开发程序员,小张:现实就来了个下马威......
- [add conditional behavior in kotlin]
- 链表-合并两个排序的列表
- MySQL 遇到过死锁问题吗,你是如何解决的?
- The second day of SSM practice_ Project split moudle_ Basic addition, deletion, modification and query_ Batch delete_ One to one cascading query
- [translation] Why do you need an API gateway to manage access to your API?
猜你喜欢

Hello World

How about the employment prospects of Russian translation? How to do a good job of Russian translation

数据仓库:详解维度建模之事实表

The pit of mpc5744p reports an error, RTOS cannot be started, and there is a clock source problem

链表-倒数最后k个结点

ssm练习第四天_获取用户名_用户退出_用户crud_密码加密_角色_权限

Bulletgraph (bullet diagram, bullet diagram)

分布式链路追踪Jaeger在Golang中的使用
![[a little knowledge] thread pool](/img/47/7296e47b53e728d2d3b9db198243f4.png)
[a little knowledge] thread pool

MPLS实验
随机推荐
更安全、更健康、无续航焦虑,魏牌拿铁DHT-PHEV来了
Bulletgraph (bullet diagram, bullet diagram)
深入理解为什么不要使用System.out.println()
链表-合并两个排序的列表
你适合做自动化 测试吗?
LeetCode_ 1005_ Maximized array sum after K negations
Meta Cambria手柄曝光,主动追踪+多触觉回馈方案
Explain in detail the implementation of grpc client long connection mechanism
PyQt5快速开发与实战 3.5 菜单栏与工具栏
Redis persistent rdb/aof
Summary of some problems encountered in developing WinForm (continuous updating)
接口测试方案(接口测试思路)
offer-集合(1)
LeetCode_1005_K次取反后最大化的数组和
凝心聚力,心心向印!印度中资手机企业协会(CMA)正式运营!
还在用Xshell?推荐这个更现代的终端连接工具
链表-反转链表
详解 gRPC 客户端长连接机制实现
J9数字论:如何避免踩雷多头陷阱?
Oracle第二天(视图、索引、plsql、游标、存储过程和存储函数、触发器、jdbc访问存储过程和存储函数)