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

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

相关推荐
qmx_0712 分钟前
HTB-Jerry(tomcat war文件、msfvenom)
java·web安全·网络安全·tomcat
为风而战20 分钟前
IIS+Ngnix+Tomcat 部署网站 用IIS实现反向代理
java·tomcat
技术无疆2 小时前
快速开发与维护:探索 AndroidAnnotations
android·java·android studio·android-studio·androidx·代码注入
罗政5 小时前
[附源码]超简洁个人博客网站搭建+SpringBoot+Vue前后端分离
vue.js·spring boot·后端
架构文摘JGWZ5 小时前
Java 23 的12 个新特性!!
java·开发语言·学习
拾光师6 小时前
spring获取当前request
java·后端·spring
aPurpleBerry6 小时前
neo4j安装启动教程+对应的jdk配置
java·neo4j
我是苏苏6 小时前
Web开发:ABP框架2——入门级别的增删改查Demo
java·开发语言
xujinwei_gingko6 小时前
Spring IOC容器Bean对象管理-Java Config方式
java·spring
2301_789985946 小时前
Java语言程序设计基础篇_编程练习题*18.29(某个目录下的文件数目)
java·开发语言·学习