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是自定义异常类,你可以根据你的需求编写自己的自定义异常类。

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

相关推荐
9523614 分钟前
SpringBoot统一功能处理
java·spring boot·后端
Lyyaoo.18 分钟前
优惠券秒杀业务分析
java·开发语言
消失的旧时光-194318 分钟前
统一并发模型:线程、Reactor、协程本质是一件事(从线程到协程 · 第6篇·终章)
java·python·算法
勿忘初心122121 分钟前
Java 国密 SM4 加密工具类实战(Hutool + BouncyCastle)|企业级数据加密 + 兼容 JDK8
java·数据安全·数据加密·后端开发·企业级开发·国密 sm4
庞轩px25 分钟前
第8篇:原子类与CAS底层原理——无锁并发的实现
java·cas·乐观锁·aba·无锁编程·自旋
rleS IONS35 分钟前
SpringBoot中自定义Starter
java·spring boot·后端
DevilSeagull1 小时前
MySQL(2) 客户端工具和建库
开发语言·数据库·后端·mysql·服务
苍煜1 小时前
慢SQL优化实战教学
java·数据库·sql
AI进化营-智能译站1 小时前
ROS2 C++开发系列16-智能指针管理传感器句柄|告别ROS2节点内存泄漏与野指针
java·c++·算法·ai
TeDi TIVE2 小时前
springboot和springframework版本依赖关系
java·spring boot·后端