当前位置:网站首页>Unified handling of global exceptions
Unified handling of global exceptions
2022-07-26 00:09:00 【Li Linnan】
Unified handling of global exceptions
stay JavaEE Project development , Regardless of the underlying database operation process , Or the business layer process , Or the process of control layer , It's inevitable to encounter all kinds of predictable 、 Unexpected exceptions need to be handled . Each procedure handles the exception separately , Highly coupled code , The workload is heavy and not uniform , Maintenance work is also very heavy .
SpringMVC Support for exception handling , adopt SpringMVC Provides a global exception handling mechanism , It can decouple all types of exception handling from each processing process , It ensures that the function of the relevant processing process is relatively single , It also realizes the unified processing and maintenance of exception information .
Implementation of global exception Spring MVC There are many ways to handle exceptions 3 Ways of planting :
- Use Spring MVC The simple exception handler provided SimpleMappingExceptionResolver
- Realization Spring Exception handling interface HandlerExceptionResolver Customize your own exception handler
- Use @ExceptionHandler Annotation implements exception handling
Global exception handling method 1
The processor is abnormally simple to configure
To configure SimpleMappingExceptionResolver object
<!-- Configure the method of unified handling of global exceptions Bean ( Simple exception handler ) -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- An exception occurred while forwarding the page , Set the default error page (error Represents a view ) -->
<property name="defaultErrorView" value="error"></property>
<!-- When an exception occurs , Set the variable name of the exception -->
<property name="exceptionAttribute" value="ex"></property>
</bean>
You can get exception information on the exception handling page
${
ex}
Use custom exception
Parameter exception
/*** Custom exception : Parameter exception */
public class ParamsException extends RuntimeException {
private Integer code = 300;
private String msg = " Parameter exception !";
public ParamsException() {
super(" Parameter exception !");
}
public ParamsException(String msg) {
super(msg);
this.msg = msg;
}
public ParamsException(Integer code) {
super(" Parameter exception !");
this.code = code;
}
public ParamsException(Integer code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
Business exceptions
/*** Custom exception : Business exceptions */
public class BusinessException extends RuntimeException {
private Integer code = 400;
private String msg = " Business exceptions !";
public BusinessException() {
super(" Business exceptions !");
}
public BusinessException(String msg) {
super(msg);
this.msg = msg;
}
public BusinessException(Integer code) {
super(" Business exceptions !");
this.code = code;
}
public BusinessException(Integer code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
Set the mapping between custom exception and page
<!-- Set the mapping between custom exception and page -->
<property name="exceptionMappings">
<props> <!-- key: The path of the custom exception object ; Set the view name of the specific processing page in the tag -->
<prop key="com.xxxx.ssm.exception.BusinessException">buss_error</prop>
<prop key="com.xxxx.ssm.exception.ParamsException">params_error</prop>
</props>
</property>
Use SimpleMappingExceptionResolver Do exception handling , It's easy to integrate 、 It has good expansibility 、 It has no advantages such as invasiveness to existing code , But this method can only get exception information , If something goes wrong , Not applicable to cases where data other than exception is required .
Global exception handling method 2 ( recommend )
Realization HandlerExceptionResolver Interface
/*** Unified handling of global exceptions */
@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception ex) {
ModelAndView mv = new ModelAndView("error");
mv.addObject("ex", " Default error message ");
return mv;
}
}
Custom exception handling
/*** Unified handling of global exceptions */
@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception ex) {
ModelAndView mv = new ModelAndView("error");
mv.addObject("ex", " Default error message ");
// Determine whether it is a custom exception
if (ex instanceof ParamsException) {
mv.setViewName("params_error");
ParamsException e = (ParamsException) ex;
mv.addObject("ex", e.getMsg());
}
if (ex instanceof BusinessException) {
mv.setViewName("business_error");
BusinessException e = (BusinessException) ex;
mv.addObject("ex", e.getMsg());
}
return mv;
}
}
Use to implement HandlerExceptionResolver Interface exception handler for exception handling , It's easy to integrate 、 It has good expansibility 、 It has no advantages such as invasiveness to existing code , meanwhile , During exception handling, the object causing the exception can be obtained , Help to provide more detailed exception handling information .
Global exception handling method 3
Page processor inherits BaseController
public class BaseController {
@ExceptionHandler
public String exc(HttpServletRequest request, HttpServletResponse response, Exception ex) {
request.setAttribute("ex", ex);
if (ex instanceof ParamsException) {
return "error_param";
}
if (ex instanceof BusinessException) {
return "error_business";
}
return "error";
}
}
Use @ExceptionHandler Annotation implements exception handling , It's easy to integrate 、 It has good expansibility ( Just need to be exception handling Controller Class inherited from BaseController that will do )、 There is no need to attach Spring Configuration and other advantages , But this method is invasive to the existing code ( Existing code needs to be modified , Make related classes inherit from BaseController), Data other than exception cannot be obtained during exception handling .
Exception handling not caught
about Unchecked Exception for , Because code does not force capture , Often overlooked , If the runtime produces Unchecked Exception, And there is no corresponding capture and processing in the code , Then we may have to face the embarrassment of 404、500…… Wait for the server internal error prompt page .
At this time, we need a comprehensive and effective exception handling mechanism . At present, most servers also support in web.xml Pass through (Websphere/Weblogic) perhaps (Tomcat) Node configuration specific exception display page . modify web.xml file , Add the following :
<!-- Error page definition -->
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/500.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/500.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/404.jsp</location>
</error-page>
边栏推荐
- LeetCode 刷题系列 -- 931. 下降路径最小和
- “动物币”凶猛,陷阱还是机遇?2021-05-12
- 牛市还没有结束,还有下半场 2021-05-18
- 二叉树——617. 合并二叉树
- What does it mean that the web server stops responding?
- 获得JD商品详情原数据 API
- 老旧笔记本电脑变服务器(笔记本电脑+内网穿透)
- Prometheus operation and maintenance tool promtool (II) query function
- Detailed explanation of kubernetes network plug-ins - calico chapter - Overview
- 栈的表示和实现(C语言)
猜你喜欢

Kubernetes网络插件详解 - Calico篇 - 概述

FreeRTOS个人笔记-互斥量

Yolov4 tiny network structure

Detailed explanation of kubernetes network plug-ins - calico chapter - Overview
34-SparkSQL自定义函数的使用、SparkStreaming的架构及计算流程、DStream转换操作、SparkStreaming对接kafka和offset的处理

二叉树——112. 路径总和

痞子衡嵌入式:MCUXpresso IDE下将源码制作成Lib库方法及其与IAR,MDK差异

MySQL的DDL、DML和DQL的基本语法

Binary tree -- 700. Search in binary search tree

Sort fake contacts
随机推荐
Niuke / Luogu - [noip2003 popularization group] stack
Exercise (1) create a set C1 to store the elements "one", "two", "three"“
本轮牛市还能持续多久?|疑问解答 2021-05-11
Getaverse, a distant bridge to Web3
MySQL——主从复制
STM32 timer
【一库】mapbox-gl!一款开箱即用的地图引擎
网站服务器停止响应是什么意思?
NVIDIA可编程推理加速器TensorRT学习笔记(三)——加速推理
07_ UE4 advanced_ MP value of firing fireball and mechanism of attacking blood deduction
"Animal coin" is fierce, trap or opportunity? 2021-05-12
Leetcode200-查找岛屿数量详解
Binary tree related knowledge
Leetcode169-多数元素详解
[brother hero July training] day 24: linear tree
二叉树相关知识
matlab实时作出串口输出数据的图像
"Demons dance", is the bull market over? 2021-05-13
栈的表示和实现(C语言)
What is multithreading