当前位置:网站首页>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>
边栏推荐
猜你喜欢

Binary tree 101. Symmetric binary tree

SIGIR '22 recommendation system paper graph network

The items of listview will be displayed completely after expansion

Getaverse,走向Web3的远方桥梁

“群魔乱舞”,牛市是不是结束了?2021-05-13

二叉树——700.二叉搜索树中的搜索

Leetcode169-多数元素详解

J9数字论:什么是DAO模式?DAO发展过程的阻碍

Binary tree - 404. Sum of left leaves

MySQL——主从复制
随机推荐
二叉树——112. 路径总和
Binary tree - 404. Sum of left leaves
【一库】mapbox-gl!一款开箱即用的地图引擎
Observer model of behavioral model
What is multithreading
J9 number theory: what is Dao mode? Obstacles to the development of Dao
安全文档归档软件
Weight file and pre training file of yolov3
34 use of sparksql custom functions, architecture and calculation process of sparkstreaming, dstream conversion operation, and processing of sparkstreaming docking Kafka and offset
Under inflation, how to operate in the future? 2021-05-14
Kubernetes网络插件详解 - Calico篇 - 概述
牛客/洛谷——[NOIP2003 普及组]栈
京东获取推荐商品列表 API
Stm32 systeminit trap during simulation debugging
没错,请求DNS服务器还可以使用UDP协议
Article 75: writing skills of academic papers
Leetcode107-二叉树的层序遍历II详解
MySQL——主从复制
Sort fake contacts
07_ue4进阶_发射火球扣mp值和攻击扣血机制