public class BusinessException extends RuntimeException {
private int code;
private String message;
public BusinessException(int code) {
super();
this.code = code;
}
public BusinessException(int code, String message) {
super();
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return "BusinessException{" +
"code=" + code +
", message='" + message + ''' +
'}';
}
}
2.全局异常处理
可以结合@ControllerAdvice:
用法
- 结合@ExceptionHandler使用 ==> 添加统一的异常处理控制器方法
- .结合@ModelAttribute使用 ==> 使用共用方法添加渲染视图的数据模型属性
- .结合@InitBinder使用 ==> 使用共用方法初始化控制器方法调用使用的数据绑定
demo
- pom包:
4.0.0 org.example SpringBoot 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-parent 2.4.2 org.projectlombok lombok 1.18.8 org.springframework.boot spring-boot-starter-web org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.4 mysql mysql-connector-java runtime org.springframework.boot spring-boot-starter-test test com.alibaba druid-spring-boot-starter 1.2.4 org.apache.commons commons-lang3 3.9 com.alibaba fastjson 1.2.73 org.hibernate.validator hibernate-validator 6.2.0.Final org.springframework.boot spring-boot-maven-plugin org.mybatis.generator mybatis-generator-maven-plugin 1.3.7 mysql mysql-connector-java 8.0.22 src/main/resources/mybatis-generate-config.xml
- Common包下,共有两个类,分别为MyException和Result
package com.no.seckill.test.Common;
import lombok.Data;
@Data
public class MyException extends RuntimeException {
String code;
String message;
}
package com.no.seckill.test.Common;
import lombok.Data;
@Data
public class Result {
String code;
String message;
}
- GlobalHandler全局处理类:
package com.no.seckill.test.Exception;
import com.no.seckill.test.Common.MyException;
import com.no.seckill.test.Common.Result;
import com.no.seckill.test.entity.user;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.text.SimpleDateFormat;
import java.util.Date;
@RestControllerAdvice
public class GlobalHandler {
private final Logger logger = LoggerFactory.getLogger(GlobalHandler.class);
// 这里@ModelAttribute("loginUserInfo")标注的modelAttribute()方法表示会在Controller方法之前
// 执行,返回当前登录用户的UserDetails对象
@ModelAttribute("loginUserInfo")
public user modelAttribute() {
return new user("test",10);
}
// @InitBinder标注的initBinder()方法表示注册一个Date类型的类型转换器,用于将类似这样的2019-06-10
// 日期格式的字符串转换成Date对象
@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
// 这里表示Controller抛出的MethodArgumentNotValidException异常由这个方法处理
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result exceptionHandler(MethodArgumentNotValidException e) {
return null;
}
// 这里表示Controller抛出的BizException异常由这个方法处理
@ExceptionHandler(MyException.class)
public Result exceptionHandler(MyException e) {
logger.info("这是我的异常");
return null;
}
// 这里就是通用的异常处理器了,所有预料之外的Exception异常都由这里处理
@ExceptionHandler(Exception.class)
public Result exceptionHandler(Exception e) {
return null;
}
}
- Controller类:
package com.no.seckill.test.controller;
import com.no.seckill.test.Common.MyException;
import com.no.seckill.test.Common.Result;
import com.no.seckill.test.entity.user;
import com.sun.istack.internal.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
@RestController
@RequestMapping("/json/exam")
@Validated
public class ExamController {
private Logger logger = LoggerFactory.getLogger(ExamController.class);
// @Autowired
// private IExamService examService;
// ......
@PostMapping("/getExamListByOpInfo")
public Result getExamListByOpInfo(@NotNull Date examOpDate,
@ModelAttribute("loginUserInfo") user userDetails) {
logger.info("Date: " + examOpDate);
logger.info("userDetails:" + userDetails.toString());
throw new MyException();
}
}
- 这里当入参为examOpDate=2019-06-10时,Spring会使用我们上面@InitBinder注册的类型转换器将2019-06-10转换examOpDate对象:
- @ExceptionHandler标注的多个方法分别表示只处理特定的异常。这里需要注意的是当Controller抛出的某个异常多个@ExceptionHandler标注的方法都适用时,Spring会选择最具体的异常处理方法来处理,也就是说@ExceptionHandler(Exception.class)这里标注的方法优先级最低,只有当其它方法都不适用时,才会来到这里处理。
1.首先容器,在启动时,根据Spring MVC的流程,会启动DispatcherServlet
2.在DispatcherServlet类中我们重点关注“initHandlerAdapters(context)”
3.initHandlerAdapters(context)方法:获取所有实现HandlerAdapter接口的bean并保存起来。
其中有个Bean为:RequestMappingHandlerAdapter,代码如下:
public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter implements BeanFactoryAware, InitializingBean
其中“AbstractHandlerMethodAdapter ”类为:
public abstract class AbstractHandlerMethodAdapter extends WebContentGenerator implements HandlerAdapter, Ordered {
因此,RequestMappingHandlerAdapter 实现了 HandlerAdapter接口!
4.在RequestMappingHandlerAdapter 中initControllerAdviceCache(),这是一个ControllerAdvice相关的初始化函数.
5.我们深入这个代码中:
private void initControllerAdviceCache() {
if (getApplicationContext() == null) {
return;
}
List adviceBeans = ControllerAdviceBean.findAnnotatedBeans(getApplicationContext());
List
观察可以看到:
- modelAttributeAdviceCache:用于记录所有 @ControllerAdvice bean组件中的 @ModuleAttribute 方法
- initBinderAdviceCache:用于记录所有@ControllerAdvice bean组件中的 @InitBinder 方法
- requestResponseBodyAdvice:用于记录所有@ControllerAdvice + RequestBodyAdvice/ResponseBodyAdvice bean组件
6.三个cache 是如何被使用的:
requestResponseBodyAdvice的使用
在RequestMappingHandlerAdapter类中的getDefaultArgumentResolvers()方法中:
可以很清晰的看到:requestResponseBodyAdvice会被传递给RequestResponseBodyMethodProcessor/RequestPartMethodArgumentResolver/HttpEntityMethodProcessor这三个参数解析器进行使用。
modelAttributeAdviceCache
在RequestMappingHandlerAdapter类中的getModelFactory()方法中:
private ModelFactory getModelFactory(HandlerMethod handlerMethod, WebDataBinderFactory binderFactory) {
SessionAttributesHandler sessionAttrHandler = getSessionAttributesHandler(handlerMethod);
Class> handlerType = handlerMethod.getBeanType();
Set methods = this.modelAttributeCache.get(handlerType);
if (methods == null) {
methods = MethodIntrospector.selectMethods(handlerType, MODEL_ATTRIBUTE_METHODS);
this.modelAttributeCache.put(handlerType, methods);
}
List attrMethods = new ArrayList<>();
// Global methods first
this.modelAttributeAdviceCache.forEach((controllerAdviceBean, methodSet) -> {
if (controllerAdviceBean.isApplicableToBeanType(handlerType)) {
Object bean = controllerAdviceBean.resolveBean();
for (Method method : methodSet) {
attrMethods.add(createModelAttributeMethod(binderFactory, bean, method));
}
}
});
for (Method method : methods) {
Object bean = handlerMethod.getBean();
attrMethods.add(createModelAttributeMethod(binderFactory, bean, method));
}
return new ModelFactory(attrMethods, binderFactory, sessionAttrHandler);
}
private InvocableHandlerMethod createModelAttributeMethod(WebDataBinderFactory factory, Object bean, Method method) {
InvocableHandlerMethod attrMethod = new InvocableHandlerMethod(bean, method);
if (this.argumentResolvers != null) {
attrMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);
}
attrMethod.setParameterNameDiscoverer(this.parameterNameDiscoverer);
attrMethod.setDataBinderFactory(factory);
return attrMethod;
}
从此方法可以看到,getModelFactory方法使用到了modelAttributeAdviceCache,它会根据其中每个元素构造成一个InvocableHandlerMethod,最终传递给要创建的ModelFactory对象。而getModelFactory又在什么时候被使用呢 ? 它会在RequestMappingHandlerAdapter执行一个控制器方法的准备过程中被调用
initBinderAdviceCache
在RequestMappingHandlerAdapter类中的getDataBinderFactory()中:
private WebDataBinderFactory getDataBinderFactory(HandlerMethod handlerMethod) throws Exception {
Class> handlerType = handlerMethod.getBeanType();
Set methods = this.initBinderCache.get(handlerType);
if (methods == null) {
methods = MethodIntrospector.selectMethods(handlerType, INIT_BINDER_METHODS);
this.initBinderCache.put(handlerType, methods);
}
List initBinderMethods = new ArrayList<>();
// Global methods first
this.initBinderAdviceCache.forEach((controllerAdviceBean, methodSet) -> {
if (controllerAdviceBean.isApplicableToBeanType(handlerType)) {
Object bean = controllerAdviceBean.resolveBean();
for (Method method : methodSet) {
initBinderMethods.add(createInitBinderMethod(bean, method));
}
}
});
for (Method method : methods) {
Object bean = handlerMethod.getBean();
initBinderMethods.add(createInitBinderMethod(bean, method));
}
return createDataBinderFactory(initBinderMethods);
}
从此方法可以看到,getDataBinderFactory方法使用到了initBinderAdviceCache,它会根据其中每个元素构造成一个InvocableHandlerMethod,最终传递给要创建的InitBinderDataBinderFactory对象。而getDataBinderFactory又在什么时候被使用呢 ? 它会在RequestMappingHandlerAdapter执行一个控制器方法的准备过程中被调用
7.再来看DispatcherServlet的initHandlerExceptionResolvers(context)方法:
private void initHandlerExceptionResolvers(ApplicationContext context) {
this.handlerExceptionResolvers = null;
if (this.detectAllHandlerExceptionResolvers) {
// Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts.
Map matchingBeans = BeanFactoryUtils
.beansOfTypeIncludingAncestors(context, HandlerExceptionResolver.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerExceptionResolvers = new ArrayList<>(matchingBeans.values());
// We keep HandlerExceptionResolvers in sorted order.
AnnotationAwareOrderComparator.sort(this.handlerExceptionResolvers);
}
}
else {
try {
HandlerExceptionResolver her =
context.getBean(HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class);
this.handlerExceptionResolvers = Collections.singletonList(her);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, no HandlerExceptionResolver is fine too.
}
}
// Ensure we have at least some HandlerExceptionResolvers, by registering
// default HandlerExceptionResolvers if no other resolvers are found.
if (this.handlerExceptionResolvers == null) {
this.handlerExceptionResolvers = getDefaultStrategies(context, HandlerExceptionResolver.class);
if (logger.isTraceEnabled()) {
logger.trace("No HandlerExceptionResolvers declared in servlet '" + getServletName() +
"': using default strategies from DispatcherServlet.properties");
}
}
}
该方法获取所有的HandlerExceptionResolvers类
其中的ExceptionHandlerExceptionResolver类:
public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExceptionResolver implements ApplicationContextAware, InitializingBean
AbstractHandlerMethodExceptionResolver继承AbstractHandlerExceptionResolver;而AbstractHandlerExceptionResolver实现了HandlerExceptionResolvers接口,因此,ExceptionHandlerExceptionResolver也会被获取。
8.ExceptionHandlerExceptionResolver中的关键代码initExceptionHandlerAdviceCache()方法:
private void initExceptionHandlerAdviceCache() {
if (getApplicationContext() == null) {
return;
}
List adviceBeans = ControllerAdviceBean.findAnnotatedBeans(getApplicationContext());
for (ControllerAdviceBean adviceBean : adviceBeans) {
Class> beanType = adviceBean.getBeanType();
if (beanType == null) {
throw new IllegalStateException("Unresolvable type for ControllerAdviceBean: " + adviceBean);
}
ExceptionHandlerMethodResolver resolver = new ExceptionHandlerMethodResolver(beanType);
if (resolver.hasExceptionMappings()) {
this.exceptionHandlerAdviceCache.put(adviceBean, resolver);
}
if (ResponseBodyAdvice.class.isAssignableFrom(beanType)) {
this.responseBodyAdvice.add(adviceBean);
}
}
if (logger.isDebugEnabled()) {
int handlerSize = this.exceptionHandlerAdviceCache.size();
int adviceSize = this.responseBodyAdvice.size();
if (handlerSize == 0 && adviceSize == 0) {
logger.debug("ControllerAdvice beans: none");
}
else {
logger.debug("ControllerAdvice beans: " +
handlerSize + " @ExceptionHandler, " + adviceSize + " ResponseBodyAdvice");
}
}
}
该方法,当Controller抛出异常时,DispatcherServlet通过ExceptionHandlerExceptionResolver来解析异常,而ExceptionHandlerExceptionResolver又通过ExceptionHandlerMethodResolver 来解析异常, ExceptionHandlerMethodResolver 最终解析异常找到适用的@ExceptionHandler标注的方法
9.ExceptionHandlerMethodResolver 中的getMappedMethod()方法进行匹配方法:
private Method getMappedMethod(Class extends Throwable> exceptionType) {
List> matches = new ArrayList();
//找到所有适用于Controller抛出异常的处理方法,
Iterator var3 = this.mappedMethods.keySet().iterator();
while(var3.hasNext()) {
Class extends Throwable> mappedException = (Class)var3.next();
if (mappedException.isAssignableFrom(exceptionType)) {
matches.add(mappedException);
}
}
if (!matches.isEmpty()) {
if (matches.size() > 1) {
这里通过排序找到最适用的方法,排序的规则依据抛出异常相对于声明异常的深度
matches.sort(new ExceptionDepthComparator(exceptionType));
}
return (Method)this.mappedMethods.get(matches.get(0));
} else {
return NO_MATCHING_EXCEPTION_HANDLER_METHOD;
}
}



