当前位置:网站首页>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());
}
}
边栏推荐
- NPM install reports an error NPM err could not resolve dependency NPM err peer
- Synchronous / asynchronous, blocking / non blocking and IO
- Operator3-设计一个operator
- LevelFilter简介说明
- 同步/异步、阻塞/非阻塞 与 IO
- cdc source能读完MySqlSnapshotSplit 就退出嘛
- MySQL 使用客户端以及SELECT 方式查看 BLOB 类型字段内容总结
- Nodejs installation tutorial
- 一篇长文---深入理解synchronized
- Tp6 use protobuf
猜你喜欢

个人博客系统(附源码)

Vmware16 create virtual machine: win11 cannot be installed

对Vintage分析的一些学习理解

CAN&CANFD综合测试分析软件LKMaster与PCAN-Explorer 6分析软件的优势对比

CVPR2021| 基于自监督学习的多视图立体匹配 (CVPR2021)

QT基础第二天(2)qt基础部件:按钮类,布局类,输出类,输入类,容器等个别举例

Vscode remote debugging PHP solution through remotessh and Xdebug

一篇长文---深入理解synchronized

Why does ETL often become ELT or even let?

js第四天流程控制(if语句和switch语句)
随机推荐
接口测试实战项目03:执行测试用例
win11系统错误:由于找不到 iertutil.dll,无法继续执行代码。重新安装程序可能会解决此问题
微服务远程调用
Full process flow of CMOS chip manufacturing
第7节-程序的编译(预处理操作)+链接
win11VMware打开虚拟机就蓝屏重启以及启动不了的解决方案
fillder使用
JS chicken laying eggs and egg laying chickens. Who appeared earlier, object or function? Is function an instance of function?
MySQL uses the client and select methods to view the summary of blob type fields
vagrant box 集群 处理
在线问题反馈模块实战(十七):实现excel模板在线下载功能
Win11vmware turns on the virtual machine and restarts on the blue screen and the solution that cannot be started
route的meta配置项
gcc/g++的使用
0 9 布隆过滤器(Bloom Filter)
利用C语言巧妙实现棋类游戏——三子棋
H3C_利用设置缺省静态路由优先级实现出口双线路的主备功能
OCR光学字符识别方法汇总
MySQL----多表查询
It's enough for MySQL to have this article (disgusting and crazy typing 37k words, just for Bo Jun's praise!!!)