Controller层方法,进行统一异常处理

提供两种不同的方案,如下:

  1. 方案1:使用 @@ControllerAdvice (或@RestControllerAdvice), @ExceptionHandler 注解实现;
  2. 方案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层方法进行统一异常处理的更多相关文章

  1. Springboot对Controller层方法进行统一异常处理

    Controller层方法,进行统一异常处理 提供两种不同的方案,如下: 方案1:使用 @@ControllerAdvice (或@RestControllerAdvice), @ExceptionH ...

  2. springMVC中controller层方法中使用private和public问题

    楼主一直习惯使用public,偶尔手误也可能使用private,但是发觉也没啥区别,都能调用service层,注入bean. 后来做一个新项目时,发觉自己以前的写的部分功能报错,当时有点懵逼,,找了半 ...

  3. SpringBoot入门系列(十一)统一异常处理的实现

    前面介绍了Spring Boot 如何整合定时任务已经Spring Boot 如何创建异步任务和定时任务.不清楚的朋友可以看看之前的文章:<Spring Boot 入门系列文章> 接下来主 ...

  4. SpringBoot测试Controller层

    一.准备工作 1.导入测试依赖 <dependency> <groupId>org.springframework.boot</groupId> <artif ...

  5. Junit mockito 测试Controller层方法有Pageable异常

    1.问题 在使用MockMVC+Mockito模拟Service层返回的时候,当我们在Controller层中参数方法调用有Pageable对象的时候,我们会发现,我们没办法生成一个Pageable的 ...

  6. PowerMock+SpringMVC整合并测试Controller层方法

    PowerMock扩展自Mockito,实现了Mockito不支持的模拟形式的单元测试.PowerMock实现了对静态方法.构造函数.私有方法以及final方法的模拟支持,对静态初始化过程的移除等强大 ...

  7. spring security 在controller层 方法级别使用注解 @PreAuthorize("hasRole('ROLE_xxx')")设置权限拦截 ,无权限则返回403

    1.前言 以前学习的时候使用权限的拦截,一般都是对路径进行拦截 ,要么用拦截器设置拦截信息,要么是在配置文件内设置拦截信息, spring security 支持使用注解的形式 ,写在方法和接口上拦截 ...

  8. SpringBoot第十四篇:统一异常处理

    作者:追梦1819 原文:https://www.cnblogs.com/yanfei1819/p/10984081.html 版权声明:本文为博主原创文章,转载请附上博文链接! 引言   本文将谈论 ...

  9. SpringBoot接口 - 如何优雅的写Controller并统一异常处理?

    SpringBoot接口如何对异常进行统一封装,并统一返回呢?以上文的参数校验为例,如何优雅的将参数校验的错误信息统一处理并封装返回呢?@pdai 为什么要优雅的处理异常 如果我们不统一的处理异常,经 ...

随机推荐

  1. CodeForces - 1101G :(Zero XOR Subset)-less(线性基)

    You are given an array a1,a2,…,an of integer numbers. Your task is to divide the array into the maxi ...

  2. 移动Web制作——JD案例

    1.制作base.css 2.制作index.html 此时会考虑页面的流式布局 3.制作index.css 总结: 1.页面制作时应注意流式布局,各版本的兼容性. 2.页面的大体组成主要有:轮播图. ...

  3. indexedDB为何物

    https://developer.mozilla.org/zh-CN/docs/Web/API/IndexedDB_API 在前一个阶段的工作中,项目组要开发一个平台,为了做出更好的用户体验,实现快 ...

  4. mybatis下的分页,支持所有的数据库

    大家都知道,mybatis的自带分页方法只是逻辑分 页,如果数据量很大,内存一定会溢出,不知道为什么开源组织不在里面集成hibernate的物理分页处理方法!在不修改mybatis源代码的情况下, 应 ...

  5. JPI中常使用的类介绍:

    Math类: java.lang包下的 final,不可被继承, 其中的方法和属性都是静态的 其构造方法私有化了,其他类不可以使用构造方法. 向上取整:Math.ceil(double d); 向下取 ...

  6. 前端开发利器: Bootstrap + AngularJS

    http://blog.csdn.net/conquer0715/article/details/51181391 概述 在HTML5盛行的互联网时代,涌现诸多的前端html/css/js框架,基于其 ...

  7. 【usaco 2006 feb gold】 牛棚安排

    终于自己独立做出来一道题QAQ然而本校数据实在太水不能确定我是不是写对了... 原题: Farmer John的N(1<=N<=1000)头奶牛分别居住在农场所拥有的B(1<=B&l ...

  8. AspNet Core Api Restful +Swagger 发布IIS

    上一步我们创建好CoreApi 接下来在框架中加入 Swagger  并发布  到 IIS (1)首先点击依赖项>管理Nuget包 (2)输入 Swashbuckle.aspnetCore  比 ...

  9. e.target和e.srcElement

    IE下,event对象有srcElement属性,但是没有target属性; Firefox下,event对象有target属性,但是没有srcElement属性.但他们的作用是相当的,即: fire ...

  10. python 调试之assert and logging

    断言 assert assert后面跟的表达式应该是True,否则,根据程序运行的逻辑,后面的代码肯定会出错. 如果断言失败,会抛出AssertionError def foo(s): n = int ...