当前位置:网站首页>3-global exception handling
3-global exception handling
2022-07-29 07:23:00 【Zhang Shao】
exception handling (SpringMVC knowledge )
Understanding anomalies
SpringMVC Annotation processing
The processing method is When the core controller is loaded , Therefore, exceptions in parameters can be intercepted
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@Component
// Develop exception handlers using annotations
// Declare that the class is a Controller Notification class of , Once declared, the class is loaded as an exception handler
// Can be in controller Enhance the function before and after
@ControllerAdvice
public class ExceptionAdvice {
// The methods defined in the class carry @ExceptionHandler Annotated are treated as exception handlers , Add the exception type actually handled later
@ExceptionHandler(NullPointerException.class)
@ResponseBody
public String doNullException(Exception ex){
return " Null pointer exception ";
}
@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public String doArithmeticException(Exception ex){
return "ArithmeticException";
}
@ExceptionHandler(Exception.class)
@ResponseBody
public String doException(Exception ex){
return "all";
}
}
Project exception handling scheme 【 understand 】


Custom exception
Business exceptions ( user ) BusinessException
// Custom exception inheritance RuntimeException, Covering all constructors of the parent class
public class BusinessException extends RuntimeException {
public BusinessException() {
}
public BusinessException(String message) {
super(message);
}
public BusinessException(String message, Throwable cause) {
super(message, cause);
}
public BusinessException(Throwable cause) {
super(cause);
}
public BusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
System exception : SystemException
// Custom exception inheritance RuntimeException, Covering all constructors of the parent class
public class SystemException extends RuntimeException {
public SystemException() {
}
public SystemException(String message) {
super(message);
}
public SystemException(String message, Throwable cause) {
super(message, cause);
}
public SystemException(Throwable cause) {
super(cause);
}
public SystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
Other anomalies : DevelopException
// Custom exception inheritance RuntimeException, Covering all constructors of the parent class
public class DevelopException extends RuntimeException {
public DevelopException() {
}
public DevelopException(String message) {
super(message);
}
public DevelopException(String message, Throwable cause) {
super(message, cause);
}
public DevelopException(Throwable cause) {
super(cause);
}
public DevelopException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
The custom exception is wrapped as an exception
public void save(){
// If an exception occurs in the business layer , The code with exception is try...catch... Handle
// stay catch Wrap the exception that appears into a custom exception , At the same time, be sure to pass the current exception object into the custom exception , Avoid the disappearance of real exception information
try {
throw new SQLException();
} catch (SQLException e) {
throw new SystemException(" Database connection timeout !",e);
}
}
Unified handling of exceptions
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@Component
@ControllerAdvice
public class ProjectExceptionAdvice {
@ExceptionHandler(BusinessException.class)
@ResponseBody()
public String doBusinessException(Exception ex, Model m){
// Using parameter Model Transfer the data to be saved to the page , Function equivalent to ModelAndView
// The message of business exception shall be sent to the user for viewing
// m.addAttribute("msg",ex.getMessage());
return ex.getMessage();
}
@ExceptionHandler(value = {
SystemException.class})
@ResponseBody
public String doSystemException(Exception ex, Model m){
// Do not send the message of system exception to the user for viewing , Send unified information to users
// m.addAttribute("msg"," Server problem , Please contact the Administrator !");
// The actual problem phenomenon should be transmitted to redis The server , The operation and maintenance personnel can view through the background system
// The actual problems should be passed on to redis The server , The operation and maintenance personnel can view through the background system
return " Server problem , Please contact the Administrator !";
}
@ExceptionHandler(Exception.class)
@ResponseBody
public String doException(Exception ex, Model m){
// m.addAttribute("msg",ex.getMessage());
// take ex Save the object
return ex.getMessage();
}
}
Unified exception handling
@Component
@ControllerAdvice
@Log4j2
public class ProjectExceptionAdvice {
@ExceptionHandler(BusinessException.class)
@ResponseBody()
public ResponseResult doBusinessException(Exception exception, Model m){
// Using parameter Model Transfer the data to be saved to the page , Function equivalent to ModelAndView
// The message of business exception shall be sent to the user for viewing
// m.addAttribute("msg",ex.getMessage());
// return ex.getMessage();
log.error("catch exception:{}", exception.getMessage());
return ResponseResult.errorResult(500,exception.getMessage());
}
@ExceptionHandler(value = {
SystemException.class})
@ResponseBody
public ResponseResult doSystemException(Exception exception, Model m){
// Do not send the message of system exception to the user for viewing , Send unified information to users
// m.addAttribute("msg"," Server problem , Please contact the Administrator !");
// The actual problem phenomenon should be transmitted to redis The server , The operation and maintenance personnel can view through the background system
// The actual problems should be passed on to redis The server , The operation and maintenance personnel can view through the background system
// return " Server problem , Please contact the Administrator !";
log.error("catch exception:{}", exception.getMessage());
return ResponseResult.errorResult(503," Server problem , Please contact the Administrator !");
}
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseResult doException(Exception exception, Model m){
// m.addAttribute("msg",ex.getMessage());
// take ex Save the object
// Log
exception.printStackTrace();
log.error("catch exception:{}", exception.getMessage());
return ResponseResult.errorResultMessage(AppHttpCodeEnum.SERVER_ERROR,exception.getMessage());
}
}
边栏推荐
- Tp6 use protobuf
- gcc/g++的使用
- Redis Basics
- JS chicken laying eggs and egg laying chickens. Who appeared earlier, object or function? Is function an instance of function?
- 2-统一返回类DTO对象
- Fillder use
- Thoroughly understand kubernetes scheduling framework and plug-ins
- VMware16创建虚拟机:Win11无法安装
- [redis] redis development specifications and precautions
- 我,28岁,测试员,10月无情被辞:想给还在学测试 的人提个醒......
猜你喜欢

Ansible中的变量及加密

Interface test actual project 03: execute test cases

Synchronous / asynchronous, blocking / non blocking and IO

Personal blog system (with source code)

JS break and continue and return keywords

最新百亿量化私募名单

LeetCode 879. 盈利计划

js中break与continue和return关键字

Vite3.0 has been released, can you still roll it (list of new features)

Kubernetes (V) -- deploy kubernetes dashboard
随机推荐
dba
WPF简单登录页面的完成案例
When NPM is installed, it is stuck. There are five solutions
Gin template
After three years of outsourcing, the salary of automatic testing after job hopping is twice that of the original. The secret is
Latest 10 billion quantitative private placement list
Win11 system error: code execution cannot continue because ierutil.dll cannot be found. Reinstalling the program may fix this problem
Other basic monitoring items of ZABBIX
H3C_利用设置缺省静态路由优先级实现出口双线路的主备功能
Vite3.0都发布了,你还能卷得动吗(新特性一览)
[solution] error: lib/bridge_ generated. dart:837:9: Error: The parameter ‘ptr‘ of the method ‘FlutterRustB
Implementation of book borrowing management system based on C language
BeanUtils.setProperty()
Section 7 - compilation of programs (preprocessing operations) + links
NPM install reports an error NPM err could not resolve dependency NPM err peer
如何与斯堪尼亚SCANIA建立EDI连接?
MySQL - multi table query
route的meta配置项
LeetCode 879. 盈利计划
Kubernetes (五) ---------部署 Kubernetes Dashboard