SpringMVC @ControllerAdvice 注解
所属分类 springboot
浏览量 967
全局异常处理
全局数据绑定
全局数据预处理
@RestControllerAdvice 与 @ControllerAdvice的区别
@RestController 与 @Controller 区别类似
@RestControllerAdvice = @ControllerAdvice + @ResponseBody
@ExceptionHandler 异常处理 ( 可定义各种异常的处理)
@InitBinder request 自定义参数解析方式注册
@ModelAttribute 可返回值或直接操作model
@ExceptionHandler(value = Exception.class)
@ExceptionHandler(value = RuntimeException.class)
@InitBinder
public void globalInitBinder(WebDataBinder binder) {
binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
}
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date';
nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2021-02-01';
nested exception is java.lang.IllegalArgumentException
@ModelAttribute(value = "globalMessage")
public String globalModelAttribute() {
System.out.println("globalModelAttribute set");
return "globalMessage,"+LocalDateTime.now();
}
@ModelAttribute
public void globalModelAttributeBuild(Model model) {
System.out.println("globalModelAttributeBuild run");
model.addAttribute("globalModelAttribute2", "globalModelAttribute2-"+LocalDateTime.now());
}
MyControllerAdvice
AdviceTestController
ErrorController
测试
/errorTest?error=Throwable
/errorTest?error=Error
/errorTest?error=Exception
/errorTest?error=RuntimeException
Throwable Error 异常 无法拦截处理
/advicetest?date=2021-02-01
/advicetest2?date=2021-02-01
完整代码
https://gitee.com/dyyx/springboothello
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = Exception.class)
public Object handleException(Exception ex) {
LOG.error("GlobalExceptionHandler_handleException",ex);
return ex+"";
}
}
springboot 使用 servlet 过滤器
springboot 使用 拦截器
上一篇
下一篇
eureka工作原理简介
Eureka源码要点
Hystrix实例
springboot读取配置的几种方式
feign ribbon 独立使用例子
springcloud zuul 简介