当前位置:网站首页>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());
}
}
边栏推荐
- gcc/g++的使用
- Remote invocation of microservices
- Summer summary (II)
- My personal website doesn't allow access to wechat, so I did this
- 我的个人网站不让接入微信登录,于是我做了这个
- Spark Learning Notes (VII) -- spark core core programming - RDD serialization / dependency / persistence / partition / accumulator / broadcast variables
- Vscode remote debugging PHP solution through remotessh and Xdebug
- Variables and encryption in ansible
- 反射reflect
- 20-40k | mecarmand 3D vision algorithm / software / Product Manager Recruitment
猜你喜欢

彻底搞懂kubernetes调度框架与插件

SQL优化

WPF简单登录页面的完成案例

Vmware16 create virtual machine: win11 cannot be installed

Remote invocation of microservices

论文阅读 (62):Pointer Networks

JS day 4 process control (if statement and switch statement)

Win11 system error: code execution cannot continue because ierutil.dll cannot be found. Reinstalling the program may fix this problem

Personal blog system (with source code)

VMware16创建虚拟机:无法创建新虚拟机,不具备执行此操作的权限
随机推荐
CVPR2021| 基于自监督学习的多视图立体匹配 (CVPR2021)
1-后台项目搭建
Guess the number / / generate a random number for the first time
JS 鸡生蛋与蛋生鸡问题,Object与Function究竟谁出现的更早?Function算不算Function的实例?
Vue router route cache
fillder使用
Operator3 - design an operator
Personal blog system (with source code)
Gin template
MySQL - multi table query
Thoroughly understand kubernetes scheduling framework and plug-ins
Synchronous / asynchronous, blocking / non blocking and IO
Interface test actual project 03: execute test cases
It's enough for MySQL to have this article (disgusting and crazy typing 37k words, just for Bo Jun's praise!!!)
Vite3.0都发布了,你还能卷得动吗(新特性一览)
gin 服务退出
[redis] redis development specifications and precautions
Gin Middleware
Can I specify memory parameters in SQL statements?
Win11 system error: code execution cannot continue because ierutil.dll cannot be found. Reinstalling the program may fix this problem