SpringBoot中实现全局异常处理,统一返回错误信息给前端

背景引入 :最近实现了一个限流切面类,但是在限流方法中throw异常,会直接打印到控制台,报错500,对前端很不友好。因为是注解,又没办法捕获再处理。那么怎么才能将错误码返回给前端呢?原来是全局异常处理......

切面方法:

java 复制代码
@Before(value = "AccessLimitPointcut()")
    public void handleAccessLimit(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        RateLimiter annotation = AnnotationUtils.findAnnotation(method, RateLimiter.class);
        int accessMaxTimes = annotation.count();
        long timeOut = annotation.time();
        TimeUnit timeUnit = annotation.timeUnit();
        String key = annotation.key();
        // 如果redis不存在或已经过期
        Long expire = redisTemplate.opsForValue().getOperations().getExpire(key);
        if (!redisTemplate.hasKey(key) || Objects.requireNonNull(expire).intValue() < 0) {
            redisTemplate.opsForValue().set(key, 1, timeOut, timeUnit);
        } else {
            long increment = redisTemplate.opsForValue().increment(key).intValue();
            if (increment > accessMaxTimes) {
                throw new AIDocException("PA-COM-000001", "访问已经超过最大值: " + accessMaxTimes);
            }
        }
    }

如果没有引入全局异常处理,那么异常会直接展示在控制台

如何实现:用@RestControllerAdvice和@ExceptionHandler注解在SpringBoot中实现全局异常处理

1、@RestControllerAdvice 注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@RequestMapping中。

2、@RestControllerAdvice 是组件注解,他使得其实现类能够被classpath扫描自动发现,如果应用是通过MVC命令空间或MVC Java编程方式配置,那么该特性默认是自动开启的。

java 复制代码
@RestControllerAdvice
public class AIDocExceptionHandler {
	
	private Logger logger = LoggerFactory.getLogger(AIDocExceptionHandler.class);

	/**
	 * 处理自定义异常
	 */
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public Map<String, Object> handleRRException(Exception e) {
		Map<String, Object> map = new HashMap<>();
		if (e instanceof AIDocException) {
			map.put("code",((AIDocException) e).getCode());
			map.put("msg", ((AIDocException) e).getMsg());
		}else {
			logger.error("【系统异常】{}", e);
			map.put("code", ErrorConstants.INVOKE_FAIL);
			map.put("msg","未知异常!");
		}
		return map;
	}
}

其中AIDocException是自定义异常类,你可以根据你的需求编写自己的自定义异常类。

以上就实现了全局统一异常管理,是不是很简单?

相关推荐
海边的Kurisu3 小时前
苍穹外卖日记 | Day1 苍穹外卖概述、开发环境搭建、接口文档
java
uzong5 小时前
后端线上发布计划模板
后端
C雨后彩虹6 小时前
任务最优调度
java·数据结构·算法·华为·面试
uzong6 小时前
软件工程师应该关注的几种 UML 图
后端
heartbeat..6 小时前
Spring AOP 全面详解(通俗易懂 + 核心知识点 + 完整案例)
java·数据库·spring·aop
Jing_jing_X6 小时前
AI分析不同阶层思维 二:Spring 的事务在什么情况下会失效?
java·spring·架构·提升·薪资
上进小菜猪7 小时前
基于 YOLOv8 的 100 类中药材智能识别实战 [目标检测完整源码]
后端
元Y亨H8 小时前
Nacos - 服务发现
java·微服务
微露清风9 小时前
系统性学习C++-第十八讲-封装红黑树实现myset与mymap
java·c++·学习
dasi02279 小时前
Java趣闻
java