spring 或 springboot统一异常处理
https://blog.csdn.net/xzmeasy/article/details/76150370
一,本文介绍spring MVC的自定义异常处理,即在Controller中抛出自定义的异常时,客户端收到更友好的JSON格式的提示。而不是常见的报错页面。
二,场景描述:实现公用API,验证API key的逻辑,放在拦截器中判断(等同于在Controller中)并抛出异常,用户收到类似下图的提示:
其中,Http状态Code也能自由控制。
三,解决方案:
1,在RateLimitInterceptor.Java拦截器中抛出异常:
[java] view plain copy
- public class RateLimitInterceptor extends HandlerInterceptorAdapter{
- @Autowired private RedisService rs;
- /**
- * 流量控制检查入口
- */
- @Override
- public boolean preHandle(HttpServletRequest request,
- HttpServletResponse response, Object handler) throws RequiredParameterException, SignException, RateLimitException,Exception {
- super.preHandle(request, response, handler);
- String appKey = request.getParameter("appKey");
- //判断appKey是否为空或是否合法
- if(appKey == null){
- throw new RequiredParameterException("");
- }else if(AppKeyUtils.isFormatCorrect(appKey) || !rs.isExist(appKey)){
- throw new SignException();
- }else {
- try {
- AppCall appCall = AppCall.create(appKey, AppKeyUtils.getPlanDetails(appKey));
- appCall.decrease();
- rs.save(appCall);
- System.out.println("RateLimitInterceptor pass.");
- } catch (RateLimitException e) {
- //抛出超限异常
- throw new RateLimitException();
- }
- }
- return true;
- }
- }
原文地址:https://www.cnblogs.com/chengjun/p/9234562.html
时间: 2024-10-08 23:46:26