【异常处理】Springboot对Controller层方法进行统一异常处理
Controller层方法,进行统一异常处理
提供两种不同的方案,如下:
- 方案1:使用 @@ControllerAdvice (或@RestControllerAdvice), @ExceptionHandler 注解实现;
- 方案2: 使用AOP技术实现;
现在分别介绍
方案1: 使用@ControllerAdvice 和 @ExceptionHandler
@ControllerAdvice 或 @RestControllerAdvice
使用@ControllerAdvice注解来增强所有的 @RequestMapping标记的方法;
官方解释:
It is typically used to define @ExceptionHandler ,@InitBinder, and @ModelAttribute methods that apply to all @RequestMapping methods.
@ExceptionHandler
- 只能声明方法;
- 与
@ControllerAdvice结合使用,可以用于增强所有@RequestMapping方法的异常处理;
核心代码
完整代码请参考: Springboot对Controller层方法进行统一异常处理
@RestControllerAdvice
public class ControllerExceptionHandleAdvice {
private final static Logger logger = LoggerFactory.getLogger(ControllerExceptionHandleAdvice.class);
@ExceptionHandler
public ResultEntity handler(HttpServletRequest req, HttpServletResponse res, Exception e) {
logger.info("Restful Http请求发生异常...");
if (res.getStatus() == HttpStatus.BAD_REQUEST.value()) {
logger.info("修改返回状态值为200");
res.setStatus(HttpStatus.OK.value());
}
if (e instanceof NullPointerException) {
logger.error("代码00:" + e.getMessage(), e);
return ResultEntity.fail("发生空指针异常");
} else if (e instanceof IllegalArgumentException) {
logger.error("代码01:" + e.getMessage(), e);
return ResultEntity.fail("请求参数类型不匹配");
} else if (e instanceof SQLException) {
logger.error("代码02:" + e.getMessage(), e);
return ResultEntity.fail("数据库访问异常");
} else {
logger.error("代码99:" + e.getMessage(), e);
return ResultEntity.fail("服务器代码发生异常,请联系管理员");
}
}
}
方案2:使用AOP技术
完整代码: 【AOP】Springboot对Controller层方法进行统一异常处理
核心代码
- @Aspect 注解;
- 织入点:
- 方法返回值为:ResultEntity
- 所有带有controller层级的包 下面的 所有类的所有方法
- @Around("execution(public com.ssslinppp.model.ResultEntity com...controller...*(..))")
@Component
@Aspect
public class ControllerAspect {
public static final Logger logger = LoggerFactory.getLogger(ControllerAspect.class);
@Around("execution(public com.ssslinppp.model.ResultEntity com..*.controller..*.*(..))")
public Object handleControllerMethod(ProceedingJoinPoint pjp) {
Stopwatch stopwatch = Stopwatch.createStarted();
ResultEntity<?> resultEntity;
try {
logger.info("执行Controller开始: " + pjp.getSignature() + " 参数:" + Lists.newArrayList(pjp.getArgs()).toString());
resultEntity = (ResultEntity<?>) pjp.proceed(pjp.getArgs());
logger.info("执行Controller结束: " + pjp.getSignature() + ", 返回值:" + resultEntity.toString());
logger.info("耗时:" + stopwatch.stop().elapsed(TimeUnit.MILLISECONDS) + "(毫秒).");
} catch (Throwable throwable) {
resultEntity = handlerException(pjp, throwable);
}
return resultEntity;
}
private ResultEntity<?> handlerException(ProceedingJoinPoint pjp, Throwable e) {
ResultEntity<?> resultEntity = null;
if (e instanceof RuntimeException) {
logger.error("RuntimeException{方法:" + pjp.getSignature() + ", 参数:" + pjp.getArgs() + ",异常:" + e.getMessage() + "}", e);
resultEntity = ResultEntity.fail(e.getMessage());
} else {
logger.error("异常{方法:" + pjp.getSignature() + ", 参数:" + pjp.getArgs() + ",异常:" + e.getMessage() + "}", e);
resultEntity = ResultEntity.fail(e.getMessage());
}
return resultEntity;
}
}
【异常处理】Springboot对Controller层方法进行统一异常处理的更多相关文章
- Springboot对Controller层方法进行统一异常处理
Controller层方法,进行统一异常处理 提供两种不同的方案,如下: 方案1:使用 @@ControllerAdvice (或@RestControllerAdvice), @ExceptionH ...
- springMVC中controller层方法中使用private和public问题
楼主一直习惯使用public,偶尔手误也可能使用private,但是发觉也没啥区别,都能调用service层,注入bean. 后来做一个新项目时,发觉自己以前的写的部分功能报错,当时有点懵逼,,找了半 ...
- SpringBoot入门系列(十一)统一异常处理的实现
前面介绍了Spring Boot 如何整合定时任务已经Spring Boot 如何创建异步任务和定时任务.不清楚的朋友可以看看之前的文章:<Spring Boot 入门系列文章> 接下来主 ...
- SpringBoot测试Controller层
一.准备工作 1.导入测试依赖 <dependency> <groupId>org.springframework.boot</groupId> <artif ...
- Junit mockito 测试Controller层方法有Pageable异常
1.问题 在使用MockMVC+Mockito模拟Service层返回的时候,当我们在Controller层中参数方法调用有Pageable对象的时候,我们会发现,我们没办法生成一个Pageable的 ...
- PowerMock+SpringMVC整合并测试Controller层方法
PowerMock扩展自Mockito,实现了Mockito不支持的模拟形式的单元测试.PowerMock实现了对静态方法.构造函数.私有方法以及final方法的模拟支持,对静态初始化过程的移除等强大 ...
- spring security 在controller层 方法级别使用注解 @PreAuthorize("hasRole('ROLE_xxx')")设置权限拦截 ,无权限则返回403
1.前言 以前学习的时候使用权限的拦截,一般都是对路径进行拦截 ,要么用拦截器设置拦截信息,要么是在配置文件内设置拦截信息, spring security 支持使用注解的形式 ,写在方法和接口上拦截 ...
- SpringBoot第十四篇:统一异常处理
作者:追梦1819 原文:https://www.cnblogs.com/yanfei1819/p/10984081.html 版权声明:本文为博主原创文章,转载请附上博文链接! 引言 本文将谈论 ...
- SpringBoot接口 - 如何优雅的写Controller并统一异常处理?
SpringBoot接口如何对异常进行统一封装,并统一返回呢?以上文的参数校验为例,如何优雅的将参数校验的错误信息统一处理并封装返回呢?@pdai 为什么要优雅的处理异常 如果我们不统一的处理异常,经 ...
随机推荐
- JS中数据类型的判断
typeof 使用 : var n = "hello"; console.log(typeof n); console.log(typeof(n));
- [LeetCode&Python] Problem 21. Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing t ...
- Javascript 标准参考教程
http://javascript.ruanyifeng.com/grammar/array.html
- centos安装jdk1.8
一.安装Java环境 1. 删除系统预装的opensdk或其他sdk 用命令 java -version 验证是否存在sdk 2. 下载Java JDK约定的版本 版本:Java SE Develop ...
- Blender 作的鸭脖
鸭脖...https://www.youtube.com/watch?v=JS8V4_Ncn0w 新建一段骨骼,编辑,[E]挤出生成3段, 或者[W]细分回到物体模式,选中骨骼,属性编辑器\物体数据\ ...
- (4)MySQL的外键(不同表之间的数据关联)
问题:下列这张表中部门等列名下输入的数据没有约束,那么可以随便填写符合规则的数据但是不符合实际需求的值,这样就造成了不符合规则的数据在表中存在,外键就是为了解决这个问题,管理员可以在另一张表中设置好符 ...
- &,~,|,^
与.或.异或的运算 与运算 (“ & ”) 参与运算的两个数据,按照二进制位进行“与运算”.运算规则:0&0=0; 0&1=0; 1&0=0; 1& ...
- 原版win10
windows10专业版:ed2k://|file|cn_windows_10_multiple_editions_x64_dvd_6848463.iso|4303300608|94FD861E824 ...
- Python知识点整理,基础3 - 字典操作
- 将koa+vue部署到服务器
很久很久以前,就对前后端如何分离,后端如何把代码部署到服务器有浓厚的兴趣,最近在阿里云上申请了一个服务器,试试水吧! 本文参考了文章<基于Node的Koa2项目从创建到打包到云服务器指南> ...